我有一个数据库class
,如:
rlock = RLock()
class PostgresDB:
host = Settings.DB_HOST
name = Settings.DB_NAME
username = Settings.DB_USERNAME
pwd = Settings.DB_PWD
def __init__(self):
self.con = None
def _create_connection(self):
if self.con is None or self.con.closed:
self.con = psycopg2.connect("host={h} dbname={n} user={u} password={p}".format(
h=self.host, n=self.name, u=self.username, p=self.pwd,
cursor_factory=RealDictCursor))
@contextlib.contextmanager
def reading_cursor(self, sql, params=None):
rlock.acquire()
self._create_connection()
try:
cur = self.con.cursor()
cur.execute(sql, params)
yield cur
except DatabaseError as e:
traceback.print_exc()
yield Exception()
finally:
self.con.close()
rlock.release()
@contextlib.contextmanager
def writing_cursor(self, sql, params=None):
rlock.acquire()
self._create_connection()
try:
cur = self.con.cursor()
cur.execute(sql, params)
yield cur
self.con.commit()
except DatabaseError as e:
traceback.print_exc()
yield Exception()
finally:
self.con.close()
rlock.release()
请注意,我明确要求RealDictCursor
。
但是,当完成任何请求时,结果是tuples
的列表,而不是dicts
。我不确定我错过了什么?
答案 0 :(得分:0)
好的,这是非常愚蠢的...如果仔细观察,你会看到我将else
传递给cursor_factory
,而不是将其传递给.format()
......