Skip to main content
 首页 » 编程设计

python之Gunicorn 导入错误 : No module name app only when directory name is site

2024年10月01日30落叶无声

尝试使用 hello world 应用程序让 gunicorn 运行。
这是我的项目目录结构

Project 
  |_ config 
  |  |_ ___init__.py 
  |  |_ settings.py 
  | 
  |_ instance 
  |  |_settings.py_production 
  | 
  |_ site 
  |  |_ __init__.py 
  |  |_ app.py 
  | 
  |_ .env 
  |_ docker-compose.yml 
  |_ Dockerfile 
  |_ requirements.txt 

我在 docker 容器中运行它,但是当我以交互模式进入容器时,会发生相同的行为。

当目录被命名为 site 并且我运行命令 gunicorn -b 0.0.0.0:8000 --access-logfile - "site.app:create_app()" 我收到错误 ImportError: No module name app。但是,如果我将目录命名为 foo、snakeeyes 或 blah,我不会收到错误并且应用程序会按预期运行。是否有一个原因?目录不能命名为站点吗? python 中还有其他受限制的目录名称吗?

请您参考如下方法:

site 是 standard library 的一部分在 python 。我假设(但不是肯定的)您正在经历冲突。

site 不是 python 中的保留字。如果您对标准关键字感兴趣,可以查看此 SO 帖子:Is the list of Python reserved words and builtins available in a library?

我认为您可以按照文档的指示通过抑制库的自动导入来测试这是否是冲突:

This module is automatically imported during initialization. The automatic import can be suppressed using the interpreter’s -S option.