不久前,我开始学习python,并创建了一个命令行应用程序,该应用程序使用sqlite3数据库管理您的家庭酒吧和鸡尾酒食谱(您可以向其中添加酒精瓶、添加食谱、检查是否有用于创建给定鸡尾酒的配料等)。名为BarmanShell
的类是该应用程序的一种api,它包含用户可以使用的每个函数
该类的__init__
包含基于xml文件的db连接和数据验证
现在,当我学习django时,我想在这个应用程序的web版本中重用它。在这个django项目中,我有一个appmyshelf
,它必须使用一些BarmanShell
功能
def myshelf_view(request, *args, **kwargs):
if request.method == "GET":
barman = BarmanShell()
shelf = barman.getShelf()
# do some things to create context based on shelf
barman = BarmanShell()
只能执行一次,而不是每个GET请求。但是我不能将它从myshelf_view
函数上移
barman = BarmanShell()
def myshelf_view(request, *args, **kwargs):
if request.method == "GET":
shelf = barman.getShelf()
# do some things to create context based on shelf
由于它包含一些sql查询,因此产生以下错误:
SQLite objects created in a thread can only be used in that same thread.
此外,我不能将其创建移动到django_project/urls.py
,然后将其导入myshelf/views.py
barman = BarmanShell() # in urls.py
from django_project.urls import barman # in views.py
因为它给出了一个错误
ImportError: cannot import name 'barman' from partially initialized module 'django_project.urls' (most likely due to a circular import)
有没有一种方法可以只对该对象进行一次克里特化,然后在django中重用它,而不必进行大的BarmanShell
重构,比如使所有函数都是静态的
巴曼谢尔级MWE:
class BarmanShell:
def __init__(self):
self.conn = sqlite3.connect("db.sqlite3")
self.cur = self.conn.cursor()
self.cur.execute('''CREATE TABLE IF NOT EXISTS SHELF
(ID INTEGER,
NAME TEXT NOT NULL,
QTY INTEGER NOT NULL,
PRIMARY KEY(ID, NAME));''')
self.conn.commit()
def getShelf(self):
return self.cur.execute("SELECT NAME, QTY FROM SHELF").fetchall()
我想如果你把数据库连接好一切都会正常的, 这个代码对我有用
对象只创建一次
相关问题 更多 >
编程相关推荐