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.


@contextmanager
def db_wrap():
conn = pool.getconn()
dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur = conn.cursor()
try:
yield conn, cur, dict_cur
finally:
pool.putconn(conn)

and to use it:

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

Rather elegant 🙂

Official docs: http://docs.python.org/library/contextlib.html

Loki

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply