I have a bunch of python methods that follow this pattern:
def delete_session(guid):
conn = get_conn()
cur = conn.cursor()
cur.execute(\"delete
Careful about that execute
, the second argument needs to be [guid] (a list with just one item). As for your question, I normally just use a class encapsulating connection and cursor, but it looks like you may prefer to use an execution context object whose __enter__
method gives you a cursor while __leave__
commits or rollbacks depending on whether the termination was normal or by exception; this would make your code
def delete_session():
with get_cursor() as cur:
cur.execute(etc etc)
If you like this style, let us know and I'll show you how to write get_cursor
. Others will no doubt propose a decorator instead, so you'd write:
@withcursor
def delete_session(cur):
cur.execute(etc etc)
but I think this makes commit/rollback, among other issues, a bit murkier. Still, if this is your preference, again let us know and I can show you how to write that form, too.