looking for a more pythonic way to access the database

前端 未结 6 1252
盖世英雄少女心
盖世英雄少女心 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条回答
  •  旧时难觅i
    2021-01-01 04:58

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

    This is confusing.

    Either you have a bunch of functions, or you have a bunch of methods of a class.

    Bunch of Functions.

    Do this instead.

    class SQLFunction( object ):
        def __init__( self, connection ):
            self.connection = connection
        def __call__( self, args=None ):
            self.cursor= self.connection.cursor()
            self.run( args )
            self.cursor.commit()
            self.cursor.close()
    
    class DeleteSession( SQLFunction ):
        def run( self, args ):
            self.cursor.execute( "statement" )
    
    delete_session = DeleteSession( connection )
    

    Your function declarations are two lines longer, but essentially the same. You can do func1( args ) because it's a callable object. The rest of your program should remain unchanged.

    Bunch of Methods in One Class.

    class SomeClass( object ):
        def __init__( self, connection ):
            self.connection= connection
        def sql_execute( self, statement, args= None )
            self.cursor= self.connection.cursor() 
            self.cursor.execute( statement, args if args is not None else [] )
            self.connection.commit()
            self.cursor.close()
        def delete_session( self ):
            self.sql_execute( "statement" )
    

    All your methods can look like delete_session and make use of a common sql_execute method.

提交回复
热议问题