推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
yezheyu
V2EX  ›  Python

关于 django 中模块导入的一点疑问

  •  
  •   yezheyu · Mar 26, 2021 · 1955 views
    This topic created in 1872 days ago, the information mentioned may be changed or developed.

    场景是:在 test.py 这个独立的测试脚本中要使用 django 项目的模型类。

    我看别人博客使用这种方式导入的:

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blog.settings') import django django.setup() import blog.models

    test.py 脚本中直接导入项目的模型类,因为 models 不在 test.py 的工作目录下,不应该是设置环境变量 PYTHONPATH,把 models 模块路径添加到 sys.path 搜索路径下吗?

    那上面设置 DJANGO_SETTINGS_MODULE 环境变量,然后 django.setup() 有什么用? 是使用 django 从 DJANGO_SETTINGS_MODULE 环境变量中加载配置启动 app,内部把所有用到模块加载到内存,因此就可以直接使用 blog.models 导入是吗?本质是使用 test.py 文件替代了 manage.py 文件作为项目的入口启动文件是吗?

    那为什么使用 celery 时只设置环境变量不用 django.setup()?

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5924 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 02:50 · PVG 10:50 · LAX 19:50 · JFK 22:50
    ♥ Do have faith in what you're doing.