如何扩展`psycopg2.extras.DictCursor`?

时间:2014-12-16 11:42:54

标签: python psycopg2

我想使用python3-psycopg2(2.5.4)游标,它可以:

1)以类似dict的方式访问查询结果

2)使用logging模块自动记录此游标执行的每个sql

我尝试了以下代码,它没有工作,我做错了什么?我可以延长psycopg2.extensions.cursor,但这不允许我做1)。

class LoggingCursor(psycopg2.extras.DictCursor):
    def __init__(self, *args, **kwargs):  # it didn't work with or
        super().__init__(*args, **kwargs) # without these 2 lines

    def execute(self, sql, args=None):
        from beautiful import app
        # logger = blah blah
        logger.debug(self.mogrify(sql, args).decode())
        psycopg2.extensions.cursor.execute(self, sql, args)

cursor = db_conn.cursor(cursor_factory=LoggingCursor)

当我cursor.execute(some_sql)时,它会给我:

File "some_file.py", line 123, in some_function
  some_var = cursor.fetchone()
File "/usr/local/lib/python3.4/dist-packages/psycopg2/extras.py", line 63, in fetchone
  res = super(DictCursorBase, self).fetchone()
File "/usr/local/lib/python3.4/dist-packages/psycopg2/extras.py", line 139, in __init__
  self._index = cursor.index

AttributeError: 'LoggingCursor' object has no attribute 'index'

1 个答案:

答案 0 :(得分:1)

如何改变

psycopg2.extensions.cursor.execute(self, sql, args)

super().execute(sql, args)

以便调用基类execute()方法?