looking for a more pythonic way to access the database

前端 未结 6 1214
盖世英雄少女心
盖世英雄少女心 2021-01-01 04:43

I have a bunch of python methods that follow this pattern:

def delete_session(guid):
    conn = get_conn()
    cur = conn.cursor()

    cur.execute(\"delete          


        
6条回答
  •  别那么骄傲
    2021-01-01 05:01

    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.

提交回复
热议问题