当我在一个函数中声明了多个连接时,如何确保连接关闭?

How to ensure connection closing, when I'm having multiple connections declared in one function?

我必须在我的函数中声明多个连接,并且我正在使用 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?

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

但是 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

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