Jhonata Antunes
Jhonata Antunes

Reputation: 51

Django: create object when server starts and use it in views

I have an image detector module, that takes about one minute to load. I would like to instantiate it once when the server starts, and use it in views. I know that i can run code when the server starts at urls.py, so, i tried the following:

urls.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()

views.py

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


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

This approach did not work, because i can not import any variables from this file. Besides that, if urls.py die, i would get NameError: name 'module' is not defined. I do not use data base, i only want a REST API to my module. I would like to use Djongo, because i will use it in other services in my project.

Summing up: i want a place to instantiate an object once when server starts, and be able to use my object in views.

Thanks!

Upvotes: 3

Views: 1610

Answers (1)

C14L
C14L

Reputation: 12558

That goes best in the models.py of the specific app that uses it. But during development, this

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

will print out two lines with two different pids. That is, because during development, Django uses the first process for the auto-reload feature. To disable that, turn off auto-reload with: ./manage.py runserver --noreload.

And now you can do

# 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.

Upvotes: 3

Related Questions