Running startup code right after Django settings? (also for commands)

混江龙づ霸主 提交于 2019-11-27 07:48:03

问题


I am using mongoengine and would like to run connect() after settings (not inside them as suggested in its docs). This is actually more like a general question how to run code right after all settings are loaded.

Update: I need a solution for management commands as well. Common approach is adding a middleware with exception MiddlewareNotUsed or adding code to root urls.py, but both don't work for commands.


回答1:


The normal place for startup-like code is in a urls.py (when you need the settings to be already loaded). Django doesn't have a good spot yet for this.

(There is an "app refactor" branch that a gsoc student worked on in 2011, but it didn't get merged into core django yet. This "app refactor" includes a solution to your very problem, but that doesn't help you...)

You mention that a management command also needs it. Is that your own management command? Nothing stops you from importing the urls.py there, is it?

This is sadly one of the few Django weak points. Luckily there aren't that many :-)



来源:https://stackoverflow.com/questions/9259844/running-startup-code-right-after-django-settings-also-for-commands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!