Last active
August 9, 2018 11:21
-
-
Save kenvac/be6a89b0e17d86ccf88a6fdd2d9666f8 to your computer and use it in GitHub Desktop.
Passing connections to functions using a decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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