[英]Python, re-entering the `with` block
I am currently working on an import script that import listings from a database that regularly shuts down every 15 mins for re-snap. 我目前正在开发一个导入脚本,该脚本从数据库导入列表,该数据库每15分钟定期关闭以重新捕捉。
I have created a with
block as below to look after the retry mechanism when creating connections: 我创建了一个with
块,如下所示,在创建连接时管理重试机制:
class DBRetryController(object):
conn_obj = None
connection = None
cursor = None
retry_count_down = None
sleep_time = None
def __init__(self, conn_obj, retry_count_down=5, sleep_time=10):
self.conn_obj = conn_obj
self.retry_count_down = retry_count_down
self.sleep_time = sleep_time
def __enter__(self):
ex = None
while self.retry_count_down > 0:
try:
if hasattr(self.conn_obj, '__call__'):
self.connection = self.conn_obj()
else:
self.connection = self.conn_obj
self.cursor = self.connection.cursor()
self.retry_count_down = False
except OperationalError as ex:
log.warning('Caught db error, possibly due to sql server gone away, retrying in a few moment')
self.retry_count_down -= 1
time.sleep(self.sleep_time)
if ex:
raise ex
return self.connection, self.cursor
def __exit__(self, type, value, traceback):
try:
self.cursor.close()
self.connection.close()
except:
pass
if value:
raise value
And use as below: 使用方法如下:
with DBRetryController(self.connection) as (_, cursor):
cursor.execute(self.LISTING_QUERY)
But the problem is the server can shutdown during execution of the query, is it possible to modifying the DBRetryController
to make the nested block of code to re-enter? 但问题是服务器可以在执行查询期间关闭,是否可以修改DBRetryController
以使嵌套的代码块重新进入?
If I understand your question correctly, I think you can use such a scheme: 如果我理解你的问题,我认为你可以使用这样的方案:
notCompleted = 1
class TestClass():
def run(self):
global notCompleted
notCompleted = 1
#do_something here
notCompleted = 0
test = TestClass()
test.run()
while(notCompleted):
test.run()
Let assume that I want to be sure, even if any error occure during execution of run()
method, my program will retry to finish to run it complete again. 假设我想确定,即使在执行run()
方法期间发生任何错误,我的程序也会重试完成再次运行它。 The notCompleted
is 1
by default. 默认情况下, notCompleted
为1
。 when I call the run
method at the beginning I assign 1
to it and at the end of my run
method I assigned 0
to it. 当我在开始时调用run
方法时,我为它分配1
,在run
方法结束时,我为它分配了0
。 Anywhere inside the run()
if I have any problem, in the while loop the function will called again. run()
任何地方如果我有任何问题,在while循环中该函数将再次调用。
I think you need to add a Try...Catch
too. 我想你也需要添加一个Try...Catch
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.