簡體   English   中英

psycopg2關閉連接池

[英]psycopg2 close connection pool

我正在開發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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM