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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With