Python – Django: Creates an object at server startup and uses it in View

Django: Creates an object at server startup and uses it in View… here is a solution to the problem.

Django: Creates an object at server startup and uses it in View

I have an image detector module and it takes about a minute to load. I want to instantiate once when the server starts and use it in View. I knew I could run code when the server started from urls.py, so, I tried the following:

URL .py

from django.contrib import admin
from django.urls import include, path

from module import Module

urlpatterns = [
    path('module/', include('project.urls')),
    path('admin/', admin.site.urls),
]

module = Module()

View .py

from django.http import HttpResponse
from project.urls import module

def end_point(request):
    module.do_stuff()
    return HttpResponse("It works!")

This method doesn’t work because I can’t import any variables from the file. Besides, if urls.py dies, I get NameError: name 'module' is not defined. I don’t use a database, I just want a REST API to my module. I want to use Djongo because I will use it in other services of my project.

Summary: I want a place to instantiate an object at server startup and be able to use my object in View.

Thanks!

Solution

Works best in the models.py of the specific application that uses it. But during development, this

# my_app/models.py
import os
mymodule = {'a': 1}
print('id: {} -- pid: {}'.format(id(mymodule), os.getpid())) 

Two lines of information with two different PIDs are printed. That is, because during development, Django uses the first process to implement automatic reloading. To disable it, turn off automatic reloading with the following command: ./manage.py runserver --noreload.

Now you can do it

# my_app/views.py
import os
from django.http import HttpResponse

from .models import mymodule                                    

def home(request):
    return HttpResponse('id: {} -- pid: {}'.format(id(mymodule), os.getpid()))

And it will print the same PID and the same ID for the mymodule object.

Related Problems and Solutions