我正在开发一个 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)
最佳答案
我相信只要您正确地关闭了每个连接中的事务,那么离开全局池应该没有任何问题。 我认为在这种情况下可能发生的最坏情况是数据库端的某些连接需要很短的时间才能确定它们已在客户端关闭 - 但这不应该导致任何数据一致性类型问题。
但是,如果您真的想在退出前关闭连接池,一种方法是注册一个atexit
函数。
import atexit
@atexit.register
def close_connection_pool():
global connection_pool
connection_pool.closeall()
关于python - psycopg2 关闭连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47018695/