Django启动导入导致发生反向
这可能是一个孤立的问题,但我想我会问一下,以防有人想到一种优雅的方法来解决它。
设置如下:
--------
views.py
--------
from django.http import HttpResponse
import shortcuts
def mood_dispatcher(request):
mood = magic_function_to_guess_my_mood(request)
return HttpResponse('Please go to %s' % shortcuts.MOODS.get(mood, somedefault))
------------
shortcuts.py
------------
MOODS = # expensive load that causes a reverse to happen
问题在于,在 django 完成构建 url 之前尝试反向操作时,shortcuts.py 会导致抛出异常。然而,views.py 还不需要导入shortcuts.py(仅在实际调用mood_dispatcher 时使用)。明显的初步解决方案是: 1)内联导入快捷方式(只是风格上不太好) 2)让shortcuts.py懒惰地构建MOODS(只是更多的工作)
<块引用>我理想的情况是能够在views.py的顶部说“除了加载url时导入快捷方式”
This might be an isolated problem, but figured I'd ask in case someone has thoughts on a graceful approach to address it.
Here's the setup:
--------
views.py
--------
from django.http import HttpResponse
import shortcuts
def mood_dispatcher(request):
mood = magic_function_to_guess_my_mood(request)
return HttpResponse('Please go to %s' % shortcuts.MOODS.get(mood, somedefault))
------------
shortcuts.py
------------
MOODS = # expensive load that causes a reverse to happen
The issue is that shortcuts.py causes an exception to be thrown when a reverse is attempted before django is done building the urls. However, views.py doesn't yet need to import shortcuts.py (used only when mood_dispatcher is actually called). Obvious initial solutions are:
1) Import shortcuts inline (just not very nice stylistically)
2) Make shortcuts.py build MOODS lazily (just more work)
What I ideally would like is to be able to say, at the top of views.py, "import shortcuts except when loading urls"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,你可以在Python中做到这一点,因为“导入”语句只是代码:
但在这种情况下,它不会非常Python化,因为快捷方式是函数mood_dispatcher的依赖项,而不是模块的依赖项本身,那么您可以在函数内部进行导入。
Python 的导入系统非常灵活和强大,但您必须注意导入顺序(同时还要避免循环依赖)。
问候
Well you can do it in python, since the "import" statement is just code:
But in this case it would not be very pythonic, since shortcuts is a dependency of the function mood_dispatcher and not of the module itself, then you could do the import inside the function.
Python's import system is very flexible and powerful but you must pay attention to the import order (and also avoid circular dependencies as well).
Regards