I’m building a Django app that is designed to be multithreaded but reside in a single process running under mod_wsgi. At start of day I need to do various, possibly-lengthy, initialization tasks such as loading a cache of data from the database into a quick lookup dict. I need the intialization to run exactly once before any requests are handled and then to kick off a background thread to periodically update the loaded data.
I’ve tried putting the initialization code inline in a module but I’ve found that sometimes (if I put load on the server when it’s starting) the init code gets executed more than once, screwing everything up.
Is there a good place to hook into Django or WSGI to run such init code exactly once before any requests are allowed in? Alternatively, does anyone know under what situations module init code gets executed more than once (particularly in djangp/WSGI-land) or of a good way to stash an “i’m already initialized flag” somewhere?
I have my initialization code in a middleware that is called when the first request is served.
After the initialization is done, you can raise a MiddlewareNotinuse exception, which causes Django not to execute that middleware again.
Remember that because of the way apache and http work, no code will be executed before the first request arrives.