Django启动导入导致发生反向

发布于 2024-08-06 17:57:36 字数 721 浏览 2 评论 0原文

这可能是一个孤立的问题,但我想我会问一下,以防有人想到一种优雅的方法来解决它。

设置如下:

--------
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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莫言歌 2024-08-13 17:57:36

好吧,你可以在Python中做到这一点,因为“导入”语句只是代码:

if some_conditional:
    import shortcuts

但在这种情况下,它不会非常Python化,因为快捷方式是函数mood_dispatcher的依赖项,而不是模块的依赖项本身,那么您可以在函数内部进行导入。

Python 的导入系统非常灵活和强大,但您必须注意导入顺序(同时还要避免循环依赖)。

问候

Well you can do it in python, since the "import" statement is just code:

if some_conditional:
    import shortcuts

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文