Skip to content

Instantly share code, notes, and snippets.

@lokori
Created May 11, 2017 10:10
Show Gist options
  • Select an option

  • Save lokori/d9126f4288fc09209611aa8e6dcd5cd7 to your computer and use it in GitHub Desktop.

Select an option

Save lokori/d9126f4288fc09209611aa8e6dcd5cd7 to your computer and use it in GitHub Desktop.
run to the db hills
# Run something in a db transaction, handle commit etc.
# f is a function which takes db cursor as a parameter for callback
def run_with_db(f):
connection = None
try:
connection = psycopg2.connect(__get_connection_string(config))
cursor = connection.cursor()
rv = f(cursor) # run something in db transaction
cursor.close()
return rv
except psycopg2.DatabaseError, exception:
print exception
sys.exit(1)
finally:
if connection:
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment