Created
June 26, 2012 15:55
-
-
Save temoto/2996642 to your computer and use it in GitHub Desktop.
[Python] psycopg2 'execute block of code in transaction' context manager
This file contains 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
@contextmanager | |
def transaction(pool='common_write'): | |
"""Context manager. | |
Executes block inside DB transaction. Returns cursor. | |
At the end of the block, the connection is returned to pool. | |
>>> with transaction() as cursor: | |
... rows = cursor.execute(...).fetchall() | |
... process(rows) | |
... cursor.execute(...) | |
""" | |
pool = random.choice(pool_map[pool]) | |
connection = pool.get() | |
try: | |
cursor = connection.cursor() | |
cursor.execute("begin") | |
try: | |
yield cursor | |
except Exception: | |
cursor.execute("rollback") | |
raise | |
else: | |
cursor.execute("commit") | |
finally: | |
connection.close() # return connection to pool |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment