Django中多个应用程序中的一个对象

2024-09-29 01:34:58 发布

您现在位置:Python中文网/ 问答频道 /正文

不久前,我开始学习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()

Tags: django函数inpyselfview应用程序request
1条回答
网友
1楼 · 发布于 2024-09-29 01:34:58

我想如果你把数据库连接好一切都会正常的, 这个代码对我有用

#url.py
from django.db import connection
class BarmanShell(object):
    def __init__(self):
        self.cur = connection.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.cur.execute('''INSERT OR REPLACE INTO SHELF VALUES (1, 'Margo', 43);''')
        
    def getShelf(self):
        return self.cur.execute("SELECT NAME, QTY FROM SHELF").fetchall()

bn = BarmanShell()
print(id(bn))

urlpatterns = [    
    path('', views.myshelf_view, kwargs={'barman':bn}, name='myshelf_view'),
]
#views.py
def myshelf_view(request, **kwargs): 
    print(id(kwargs.get('barman'))) 
    print(kwargs.get('barman').getShelf())
OUTPUT:
ID_OF_BARMAN_OBJECT
ID_OF_BARMAN_OBJECT
[('Margo', 43)]

对象只创建一次

相关问题 更多 >