psycopg2关闭连接池

use*_*968 8 python psycopg2 flask python-3.x

我正在开发Flask API,我有以下代码使用Psycopg2建立连接池.我想我应该考虑在程序终止时关闭连接池,我该怎么做?

@contextmanager
def get_cursor(:
    global connection_pool
    if not cls.connection_pool:
        cls.connection_pool = ThreadedConnectionPool(5, 25, dsn=PoolingWrap.generate_conn_string())

    con = cls.connection_pool.getconn()
    try:
        yield con.cursor(cursor_factory=RealDictCursor)
    finally:
        cls.connection_pool.putconn(con)
Run Code Online (Sandbox Code Playgroud)

Mic*_*son 5

我相信,只要您正确关闭每个连接中的事务,那么仅离开全局池就不会有任何问题。我认为在这种情况下可能发生的最糟糕的情况是,数据库端的某些连接花了很短的时间才能弄清它们已在客户端上关闭-但这不应引起任何数据一致性类型问题。

但是,如果您确实要在退出之前关闭连接池,则一种方法是注册一个atexit函数。

import atexit

@atexit.register
def close_connection_pool():
    global connection_pool
    connection_pool.closeall()
Run Code Online (Sandbox Code Playgroud)