开发者

What's a safe way to do one-off initialization in Django/mod_wsgi?

开发者 https://www.devze.com 2023-02-10 01:53 出处:网络
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

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 th开发者_如何学运维en 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.


Maybe an good old lockfile is a solution for this problem. Not a really elegant solution, but it saves you a lot of headaches in a multithreaded environment.


I have my initialization code called from the Settings.py file. The Settings.py file will only be executed once and is executed before any request is handled.

See http://code.djangoproject.com/wiki/SplitSettings for ideas about splitting up the Settings.py file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号