Managing Database Connections “with”

I’m using a pool to manage database connections. I decided to change from having per thread database connections to have per function database connections.

I was unsure of how to do this elegantly and thought decorating the the functions might be the best approach. However I really wanted to have local variables defined: enter context managers and the with statement.

def db_wrap():
conn = pool.getconn()
dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur = conn.cursor()
yield conn, cur, dict_cur

and to use it:

with db_wrap() as (conn, cur, dict_cur):
cur.execute('select stuff etc')

Rather elegant 🙂

Official docs:


0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply