简体   繁体   中英

Help interpreting Python code snippet

I found the below on the web, however from my little exposure with Python I am aware that one can attach functions to object in the fly. I am also aware that everything in Python is object. I am yet to understand what one intend to achieve with the below and its use case. This is the part I need help:

run_sql_command.c = c

def get_sql_object(c):
    def run_sql_command(command, arguments=[]):
        c.execute(command, arguments)
        return c.fetchall()
    run_sql_command.c = c
    return run_sql_command

The idea here (I believe) is that someone is creating a placeholder object that keeps reference to a cursor c so that it may be used to execute queries later. Proposed usage is probably something like this:

c = DBConnectionObject.cursor()

myExecutor = get_sql_object(c)

# some amount of code later
rows = myExecutor(Queries.GetAllUsersByFName, ['Larry', 'Bob'])

-- To address some of the comments --

I find that attempting to keep cursors around can cause problems in volatile environments where it's not always guaranteed that the database connection remains connected. I opt for this approach instead:

class DBConnection(object):
  def __init__(self, dbpath):
    self.dbPath = dbpath

    # Any connection object here, really.
    self._conn = kinterbasdb.connect()

  def cursor(self, query, params = None):
    try:
      cursor = self._conn.cursor()

      if params:
        cursor.execute(query, params)
      else:
        cursor.execute(query)

      return cursor
    except (kdb.ProgrammingError, AttributeError), e:
        print e

  def qry(self, query, params = None):
    cursor = self.cursor(query, params)

    return [[x[0].title() for x in cursor.description]] + [r for r in cursor.fetchall()]

Then, you'd create a global database connection like so:

dbcon = DBConnection('/path/to/mydb.fdb')

and run queries with:

rows = dbcon.qry(Queries.GetSomething)

or:

filtered = dbcon.qry(Queries.FilteredQuery, ['my', 'parameters'])

I've omitted some of the code that does error handling / reconnects to the database if the connection has dropped, but the general idea is there. This way, cursors are created when they're needed, used, and allowed to go out of scope, letting me centralize error handling.

我认为run_sql_command.c可以保留对c的可访问引用,例如以后将其关闭。

That line adds an attribute c to the function run_sql_command , giving it the value passed to the function get_sql_object() , presumably a database cursor. You probably already knew that much.

With the limited scope of this snippet, the statement has no use at all. In a larger context, the cursor may be re-used elsewhere in the code. Look for accesses to the .c attribute in other parts of the code, and see what's done with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM