gpt4 book ai didi

python - 如何在 console_script 中调用 django.setup()?

转载 作者:太空狗 更新时间:2023-10-29 18:01:22 26 4
gpt4 key购买 nike

当前的 django 文档告诉我这个:

django.setup() may only be called once.

Therefore, avoid putting reusable application logic in standalone scripts so that you have to import from the script elsewhere in your application. If you can’t avoid that, put the call to django.setup() inside an if block:

if __name__ == '__main__':
import django
django.setup()

来源:Calling django.setup() is required for “standalone” Django usage

我在 setup.py 中使用入口点。这样我就没有 __name__ == '__main__'

问题

如果使用 console_scripts,如何确保 django.setup() 只被调用一次?

我应该把 django.setup() 放在哪里?

背景

我遇到的实际错误:Django 挂起。原因如下:https://code.djangoproject.com/ticket/27176

我想将我的应用程序移植到当前的 django 版本。更改为管理命令不是一个选项,因为其他(第三方应用程序)依赖于我的控制台脚本的存在。

最佳答案

有同样的问题(或类似的问题)。我通过这样做解决了它:

[警告:肮脏的解决方案]

if not hasattr(django, 'apps'):
django.setup()

这样即使导入多次也只会调用一次

关于python - 如何在 console_script 中调用 django.setup()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39704298/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com