Skip to content

Instantly share code, notes, and snippets.

@kenvac
Last active August 9, 2018 11:21
Show Gist options
  • Save kenvac/be6a89b0e17d86ccf88a6fdd2d9666f8 to your computer and use it in GitHub Desktop.
Save kenvac/be6a89b0e17d86ccf88a6fdd2d9666f8 to your computer and use it in GitHub Desktop.
Passing connections to functions using a decorator
import psycopg2
from functools import wraps
from contextlib import contextmanager
from psycopg2.pool import ThreadedConnectionPool
PSQL_CONN = {
'host': '127.0.0.1',
'port': '5432',
'user': 'user',
'password': 'password',
'database': 'database'
}
pool = ThreadedConnectionPool(1, 20, **PSQL_CONN)
@contextmanager
def get_db_connection():
try:
connection = pool.getconn()
yield connection
finally:
pool.putconn(connection)
@contextmanager
def get_db_cursor(commit=False):
with get_db_connection() as connection:
cursor = connection.cursor()
try:
yield cursor
if commit:
connection.commit()
finally:
cursor.close()
with get_db_cursor() as cursor:
cusor.execute("select id from customers")
customer_ids = cursor.fetchone()
print customer_ids
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment