Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psycopg2 close connection pool

I'm developing a Flask API, and I have the following code to have a connection pool using Psycopg2. I wonder should I consider to close the connection pool when the program terminates and how should I do this?

@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)
like image 915
user1187968 Avatar asked Oct 30 '17 15:10

user1187968


People also ask

What is Postgres connection pool?

Connection pooling is the process of having a pool of active connections on the backend servers. These can be used any time a user sends a request. Instead of opening, maintaining, and closing a connection when a user sends a request, the server will assign an active connection to the user.

What does Psycopg2 Connect do?

The connection class of the psycopg2 represents/handles an instance of a connection. You can create new connections using the connect() function. This accepts the basic connection parameters such as dbname, user, password, host, port and returns a connection object.

What is commit in Psycopg2?

commit() Commit any pending transaction to the database. By default, Psycopg opens a transaction before executing the first command: if commit() is not called, the effect of any data manipulation will be lost.

What is the meaning of Psycopg2?

Psycopg2 is a DB API 2.0 compliant PostgreSQL driver that is actively developed. It is designed for multi-threaded applications and manages its own connection pool.


1 Answers

I believe that so long as you are closing the transactions in each connection correctly, then you should not have any problem just leaving the global pool. I think the worst that can happen in that case is some connections on the DB side take a short while to work out that they've been closed on the client side - but this should not be able to cause any data consistency type issues.

However, if you really want to close the connection pool before you exit, one way to do this is to register an atexit function.

import atexit

@atexit.register
def close_connection_pool():
    global connection_pool
    connection_pool.closeall()
like image 146
Michael Anderson Avatar answered Sep 30 '22 06:09

Michael Anderson