tags:

views:

350

answers:

2

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?

+5  A: 

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

TokenMacGuy
For mod_wsgi it will be once per process for that Django instance as well. How many processes that may be is dictated by whether you are using embedded mode or daemon mode and thus how many processes your Django instance is running across. For more details about different operating modes of mod_wsgi, see 'http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading'.
Graham Dumpleton
A: 

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.

Glenn Maynard