from psycopg2.pool import ThreadedConnectionPool
from psycopg2.extras import RealDictCursor
from contextlib import contextmanager
from urllib.parse import urlparse
DATABASE_URL = 'postgresql://postgres:postgres@localhost/postgres'
url = urlparse(DATABASE_URL)
pool = ThreadedConnectionPool(1, 50,
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port)
@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(cursor_factory=RealDictCursor)
try:
yield cursor
if commit:
connection.commit()
finally:
cursor.close()
# Пример использования
with get_db_cursor() as cursor:
cursor.execute("SELECT city, temp_lo, temp_hi, date FROM weather;")
data = cursor.fetchone()
with get_db_cursor(commit=True) as cursor:
cursor.callproc("SOME_PROC_NAME")