尝试从目录外部导入时出现 ModuleNotFoundError

ModuleNotFoundError when attempting to import from outside of directory

我正在开发 Flask 应用程序并尝试 运行 我的测试文件但无法这样做。我当前的应用程序结构是:

Project
── app
│   ├── __init__.py
│   ├── forms.py
│   ├── model.py
│   ├── models.py
│   ├── static
│   │   ├── css
│   │   ├── fonts
│   │   ├── img
│   │   ├── js
│   │   └── uploads
│   ├── templates
│   │   ├── client
│   │   │   ├── client-base.html
│   │   │   ├── client-inventory.html
│   │   │   ├── client-login.html
│   │   │   ├── client-macros.html
│   │   │   ├── client-main.html
│   │   │   └── client-signup.html
│   │   └── user
│   │       ├── user-base.html
│   │       ├── user-macros.html
│   │       └── user-main.html
│   └── views
│       ├── __init__.py
│       ├── client.py
│       └── user.py
├── config.py
├── run.py
└── tests
    └── test_user_model.py

当我在 test_user_model.py 中尝试 运行 from app.models import User 时,它引发了 ModuleNotFoundError: No module named 'app'。我已经尝试过无数种不同的方式来编辑 import 语句,但在每种情况下它仍然会引发错误(from ..app import models 超出范围,import app 并且类似的导入也不起作用。)

您需要在 PYTHONPATH

中添加 app

您应该在 tests 目录中添加 __init__.py。空 __init__.py 会将那个目录变成一个包。然后你可以在 test_user_model.py:

中使用这一行
from app.models import User

详见PEP 328