3

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!

  • This is not a duplicate, but might be of interest. https://stackoverflow.com/a/51082877/7692463. AKA you can use signals for that. See my implementation. – scharette Jul 09 '18 at 15:39
  • im pretty sure you should use it on your manage.py, when he first start the server using manage.py runserver he will start your module, but you must let be accesed in entire application – Diego Vinícius Jul 09 '18 at 16:26

1 Answers1

3

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.

C14L
  • 12,153
  • 4
  • 39
  • 52