简体   繁体   English

Python,重新进入`with`块

[英]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. 默认情况下, notCompleted1 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.

相关问题 是否有退出和重新输入脚本的命令? - Is there a command for exiting and re-entering a script? Kivy:在重新进入屏幕时将切换按钮重置为“正常” - Kivy: resetting toggle buttons to “normal” on re-entering screen 更新Tkinter列表框而不退出并重新进入? - Updating Tkinter listbox without quitting and re-entering? 重新进入 FOV 时修复其他客户端字符上的偏移量,(PyGame 和套接字) - fix the offset on other client's char when re-entering FOV, (PyGame and sockets) 通过从报纸收集文字重新输入代码时,所有内容都被忽略,但第一个链接 - Everything ignored but the first link when re-entering the code by gathering text from newspapers Django - 用户在注销后单击浏览器后退按钮重新进入会话 - Django - User re-entering session by clicking browser back button after logging out 如何使用户在重新进入 discord 服务器时不会删除静音角色? - How can I make it so that the user does not remove mute role when re-entering the discord server? Scipy 旋转模块在重新输入转换后的四元数时产生不同的结果 - Scipy Rotation Module produces differing results when re-entering a converted quaternion Python未输入 - Python not entering in for re.sub用于替换python中的文本块(多行) - re.sub for replacing block(multi line) of text in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM