在Django设置之后运行启动代码? (也用于命令) [英] Running startup code right after Django settings? (also for commands)
问题描述
我正在使用 mongoengine
,并希望在设置后不运行 connect()
=http://mongoengine.org/docs/v0.5/django.html =nofollow>,如其文档所示)。这实际上更像是一般的问题,如何在所有设置加载后运行代码。
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.
更新:我需要一个管理命令的解决方案。通常的方法是添加一个具有例外 MiddlewareNotUsed
或添加代码到root urls.py的中间件,但两者都不适用于命令。
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.
推荐答案
启动代码的正常位置在urls.py(当您需要设置已经加载时)。 Django还没有一个好的地方。
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.
(有一个gsoc学生在2011年工作的app refactor分支,但没有这个应用重构包含了一个解决你的问题的解决方案,但这并不能帮助你...)
(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...)
你提到一个管理命令也需要它。这是你自己的管理命令吗?没有什么阻止你导入urls.py在那里,是吗?
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?
这个是是几个Django弱点之一。幸运的是没有那么多: - )
This is sadly one of the few Django weak points. Luckily there aren't that many :-)
这篇关于在Django设置之后运行启动代码? (也用于命令)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!