Create contextmanagers.py

Context managers for a connection, a cursor given a connection, and a cursor given the db connection kwargs
This commit is contained in:
FelipeV34 2021-08-19 00:39:03 -05:00
parent 1b255b7dc3
commit 5343dff5ad

49
lib/contextmanagers.py Normal file
View File

@ -0,0 +1,49 @@
"""psycopg context managers for connections, cursors, and pools."""
from contextlib import contextmanager
from extensions import connect, cursor
@contextmanager
def connection(**kwargs):
"""Context manager to yield and close a db connection."""
connection = connect(**kwargs)
try:
yield connection
finally:
connection.close()
@contextmanager
def cursor(connection):
"""
Context manager to yield and close a cursor given an existing db
connection.
"""
cursor = connection.cursor()
try:
yield cursor
finally:
cursor.close()
@contextmanager
def connection_cursor(**kwargs):
"""
Context manager to yield a cursor and close it and its connection for
purposes or performing a single db call.
"""
connection = connect(**kwargs)
cursor = connection.cursor()
try:
yield cursor
finally:
cursor.close()
connection.close()