Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Initialization

Tags:

python

django

I have a big array, that I would like to load into memory only once when django starts up and then treat it as a read only global variable. What is the best place to put the code for the initialization of that array?

If I put it in settings.py it will be reinitialized every time the settings module is imported, correct?

like image 597
D R Avatar asked Jul 12 '09 21:07

D R


People also ask

How do I run Django initialization code only once on startup?

Basically, you can use <project>/wsgi.py to do that, and it will be run only once, when the server starts, but not when you run commands or import a particular module. Again adding a comment to confirm that this method will execute the code only once. No need for any locking mechanisms.

What is Django setup ()?

It is used if you run your Django app as standalone. It will load your settings and populate Django's application registry. You can read the detail on the Django documentation. As mentioned in the docs, django.setup() may only be called once.

What is the Django command to start a new?

at the end of the django-admin startproject command: (env) $ django-admin startproject <projectname> . The dot skips the top-level project folder and creates your management app and the manage.py file right inside your current working directory.


2 Answers

settings.py is for Django settings; it's fine to put your own settings in there, but using it for arbitrary non-configuration data structures isn't good practice.

Just put it in the module it logically belongs to, and it'll be run just once per instance. If you want to guarantee that the module is loaded on startup and not on first use later on, import that module from your top-level __init__.py to force it to be loaded immediately.

like image 171
Glenn Maynard Avatar answered Sep 27 '22 23:09

Glenn Maynard


settings.py is the right place for that. Settings.py is, like any other module, loaded once. There is still the problem of the fact that a module must be imported once for each process, so a respawning style of web server (like apache) will reload it once for each instance in question. For mod_python this will be once per process. for mod_wsgi, this is likely to be just one time, unless you have to restart.

tl;dr modules are imported once, even if multiple import statements are used. put it in settings.py

like image 32
SingleNegationElimination Avatar answered Sep 27 '22 21:09

SingleNegationElimination