0

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()
5
  • It looks like you are calling another view in this view. Normally you do not do that, since views are wrapped in transactions. This is done to guarantee that the updates on the database are done in an atomic way. Jan 16, 2021 at 15:11
  • @Willem Van Onsem i'm not. views.py beside code above contains only from django.shortcuts import render from barmanshell.barmanshell import BarmanShell
    – docp
    Jan 16, 2021 at 15:31
  • it would help if you create a minimum example of BarmanShell() class to reproduce your error.
    – Stepan
    Jan 16, 2021 at 16:14
  • @Stepan done, you can use mwe to reproduce sqlite thread error.
    – docp
    Jan 16, 2021 at 16:58
  • @docp I think you should connect to the database via django
    – Stepan
    Jan 16, 2021 at 18:08

1 Answer 1

1

I guess if you properly connect your database everything should work, this code works for me.

#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)]

The object creates just once.

1
  • just to be clear: main problem was with self.conn = sqlite3.connect("db.sqlite3")
    – docp
    Jan 17, 2021 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.