Should PostgreSQL connections be pooled in a Python web app, or create a new connection per request?

前端 未结 5 475
隐瞒了意图╮
隐瞒了意图╮ 2021-02-04 17:26

I\'m building a web app in Python (using Flask). I do not intend to use SQLAlchemy or similar ORM system, rather I\'m going to use Psycopg2 directly.

Should I open a new

5条回答
  •  清歌不尽
    2021-02-04 18:14

    Yeah connection pooling will help but yes you have to find out the right numbers for live connection or pool size based on which load will be on database.

        from psycopg2.pool import SimpleConnectionPool
        from contextlib import contextmanager
    
        dbConnection = "dbname='dbname' user='postgres' host='localhost' password='postgres'"
    
        # pool define with 10 live connections
        connectionpool = SimpleConnectionPool(1,10,dsn=dbConnection)
    
        @contextmanager
        def getcursor():
            con = connectionpool.getconn()
            try:
                yield con.cursor()
            finally:
                connectionpool.putconn(con)
    
        def main_work():
            try:
                # with here will take care of put connection when its done
                with getcursor() as cur:
                    cur.execute("select * from \"TableName\"")
                    result_set = cur.fetchall()
    
            except Exception as e:
                print "error in executing with exception: ", e
    

提交回复
热议问题