looking for a more pythonic way to access the database

前端 未结 6 1215
盖世英雄少女心
盖世英雄少女心 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 04:52

    A decorator?

    class SqlExec:
       def __init__ (self, f):
          self.f = f
       def __call__ (self, *args):
          conn = get_conn() 
          cur = conn.cursor()
          cur.execute(self.f (*args))
          conn.commit()
          conn.close()
    
    @SqlExec
    def delete_session(guid):
          return "delete from sessions where guid=%s" % guid
    

提交回复
热议问题