mirror of
https://github.com/psycopg/psycopg2.git
synced 2025-07-31 18:40:09 +03:00
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:
parent
1b255b7dc3
commit
5343dff5ad
49
lib/contextmanagers.py
Normal file
49
lib/contextmanagers.py
Normal 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()
|
Loading…
Reference in New Issue
Block a user