我如何导入位于上方(测试文件夹之外)的模块,然后返回我的应用程序文件夹结构?
在我要的app_test.py文件夹中
from app.models import User
运行
/bin/python app_test.py
我明白了
no modules named app.models
我有一个 app_test.py 文件,在我进行一些改组之前一直有效,现在我不确定为什么从我的测试文件夹运行测试时我的导入不起作用。我进入了我的应用程序主文件夹,这是基本布局减去多余的文件夹/文件:
/application
/(leaving out folders bin build lib local...)
/src
/test
__init__.py
app_test.py
/app
models.py
forms.py
__init__.py
views.py
/static
/templates
/tmp
我应该导入什么?我注意到大型教程只使用 test.py 文件而不是文件夹。这是最好的方法吗?如果不是,我的测试文件夹应该放在哪里?这让我发疯。
最佳答案
您需要从顶部运行您的 app_test.py(即“python test/app_test.py”)或修复 app_test.py 中的 python 路径:
import os
import sys
topdir = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(topdir)
关于python - 从测试文件夹导入 flask 模块失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22736850/