#python #django #class #django-database
#python #django #класс #django-база данных
Вопрос:
я пытаюсь создать оболочку пользовательского класса для «django.db.connection», но я продолжаю получать «django.db.utils.Ошибка интерфейса: курсор уже закрыт».
рабочий код выглядит примерно так, если без оболочки пользовательского класса (скопирован из ./manage.py shell
) :
>>> from django.db import (connection as con)
>>> with con.cursor() as q:
... q.execute('select * from master.years a where a.years = %s', [str(2019)])
... f = [f.name for f in q.description]
... for b in q:
... print(dict(zip(f,b)))
моя оболочка webapp/mine/db.py
:
class query_00:
def __init__(self, db_con, db_sql, db_stmt = []):
self.db_con = db_con
self.db_sql = db_sql
self.fields = []
with db_con.cursor() as self.query:
self.query.execute(db_sql, db_stmt)
self.fields = [f.name for f in self.query.description]
# for entry in self.query:
# yield dict(zip(self.fields, entry))
# self.query = db_con.cursor()
# must return self, because
# AttributeError: 'NoneType' object has no attribute 'result'
def __enter__(self):
return self
# self.query.execute(self.db_sql, self.db_stmt)
# self.fields = [f.name for f in self.query.description]
# pass
def __exit__(self, exc_type, exc_value, traceback):
# is this necessary?
# self.db_con.close()
pass
def result(self):
for entry in self.query.fetchall():
yield dict(zip(self.fields, entry))
# not working
# for entry in self.query:
# yield dict(zip(self.fields, entry))
# not working
# yield dict(zip(self.fields, entry))
# pass
затем я пробую это ./manage.py shell
, набирая
from django.db import (connection as con)
from mine.db import query_00
# expected usage, attempt 1
q = query_00(con, 'SELECT * FROM master.years a where a.year = %s', [str(2019),])
for b in q.result():
print(b)
# expected usage, attempt 2
with query_00(con, 'SELECT * FROM master.years a where a.year = %s', [str(2019),]) as q:
for b in q.result():
print(b)
python-3, django-2, postgresql-9
(извините за мой английский)
Ответ №1:
итак, после прочтения документации я понимаю, что соединение было закрыто внутри моего метода инициализации.
class query_00:
def __init__(self, db_con, db_sql, db_stmt = []):
self.db_con = db_con
self.db_sql = db_sql
self.fields = []
with db_con.cursor() as self.query:
self.query.execute(db_sql, db_stmt)
self.fields = [f.name for f in self.query.description]
# the connection only happend inside "with:" block
# the connection, was already closed here (after with:)
итак, мне просто нужно сохранить cursor() в переменной
class query_01:
def __init__(self, db_sql, db_stmt):
self.db_sql = db_sql
self.db_stmt = db_stmt
self.query = connection.cursor()
...
поместите query.execute()
другой метод
...
def execute(self):
self.query.execute(self.db_sql, self.db_stmt)
self.fields = [f.name for f in self.query.description]
...
в результате ()
...
def result(self):
self.execute()
for entry in self.query:
yield self.keyvalue(entry)
...
тогда мой класс работает
with query_00('SELECT * FROM master.years a where a.year = %s', [str(2019),]) as q:
for b in q.result():
print(b)