Some time ago I started to learn python and I created commandline application that manages your home bar and cocktails recipes (you can add alcohol bottles to it, add recipes, check if you have ingredients to create given cocktail and so on) that uses sqlite3 database. Class called BarmanShell
is kind of api of this app which contains every function user could use.
__init__
of that class contains db connection and data validation based on xml files.
Now, as I'm learning django, I would like to reuse it in web version of this application. In this django project I have app myshelf
that must use some BarmanShell
functionality.
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()
could be done only once, not every GET request. But I cannot move it up from myshelf_view
function
barman = BarmanShell()
def myshelf_view(request, *args, **kwargs):
if request.method == "GET":
shelf = barman.getShelf()
# do some things to create context based on shelf
as it contains some sql queries and following error is produced:
SQLite objects created in a thread can only be used in that same thread.
Also, I cannot move its creation to django_project/urls.py
and then import it in myshelf/views.py
barman = BarmanShell() # in urls.py
from django_project.urls import barman # in views.py
because it gives an error
ImportError: cannot import name 'barman' from partially initialized module 'django_project.urls' (most likely due to a circular import)
Is there a way to crete that object only once and then just reuse it across django without big BarmanShell
refactor such as making all functions static?
MWE of BarmanShell class:
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()