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

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

Leave a comment