【问题标题】:How to ensure connection closing, when I'm having multiple connections declared in one function?当我在一个函数中声明多个连接时,如何确保连接关闭?
【发布时间】:2019-04-01 09:17:16
【问题描述】:

我必须在我的函数中声明多个连接,并且我使用 finally 块来确保它们在出现任何异常的情况下全部关闭。然而,当在其中一个连接建立期间发生异常时,我陷入了困境。我知道按声明的顺序关闭连接将确保即使其中一个连接建立没有问题,它也会被关闭,这是肯定的。

def some_func(x_connect_params,y_connect_params):
    try:
        x_conn = psycopg2.connect(**x_connect_params)
        x_cur = x_conn.cursor()
        y_conn = psycopg2.connect(**y_connect_params)
        y_cur = y_conn.cursor()
        # SOME CODE THAT USES CONNECTIONS
    except Exception as e:
        pass
    finally:
        x_cur.close()
        x_conn.close()
        y_cur.close()
        y_conn.close()

但我在徘徊有没有办法确保关闭连接并能够避免在 finally 块中出现 UnboundLocalError?

【问题讨论】:

    标签: python exception connection psycopg2


    【解决方案1】:

    这就是上下文管理器的作用,确保资源的释放

    但是 psycopg2 上下文管理器不会关闭连接,因此您可以自己编写

    from contextlib import contextmanager
    
    import psycopg2
    
    @contextmanager
    def get_connection(connection_param):
        con = psycopg2.connect(**connection_param)
        try:
            yield con
        finally:
            con.close()
    
    @contextmanager
    def get_cursor(connection):
        cur = connection.cursor()
        try:
            yield cur
        finally:
            cur.close()
    
    
    def some_func(x_connect_params,y_connect_params):
        with get_connection(x_connect_params) as x_conn, get_connection(y_connect_params) as y_conn:
            with get_cursor(x_conn) as x_cur, get_cursor(y_conn) as y_cur:
            # SOME CODE THAT USES CONNECTIONS
    

    编辑:链接到 psycopg2 上下文管理器 https://github.com/psycopg/psycopg2/blob/3eecf34beaa0fa2deea9f22baf3b657db412a404/doc/src/usage.rst#with-statement

    【讨论】:

    • 谢谢,有帮助!
    猜你喜欢
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 2017-07-08
    相关资源
    最近更新 更多