问题
I'm working on a Flask app and attempting to run my test file but unable to do so. My current app structure is:
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
when I attempt to run from app.models import User
in test_user_model.py
it raises ModuleNotFoundError: No module named 'app'
. I've tried editing the import statement countless different ways but it still raises an error in every case (from ..app import models
is out of scope, import app
and similar imports also don't work.)
回答1:
You should add __init__.py
in your tests
directory. The empty __init__.py
will turn that directory into a package. Then you can use this line in your test_user_model.py
:
from app.models import User
See details in PEP 328.
回答2:
You need to add app
in your PYTHONPATH
来源:https://stackoverflow.com/questions/41963455/modulenotfounderror-when-attempting-to-import-from-outside-of-directory