ModuleNotFoundError when attempting to import from outside of directory

允我心安 提交于 2021-01-27 19:13:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!