从测试文件夹导入flask模块失败
我该如何导入位于测试文件夹上层(也就是在测试文件夹外面)的模块,然后再回到我的应用文件夹结构中呢?
在 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 文件,而不是文件夹。这是最好的做法吗?如果不是,我的测试文件夹应该放在哪里?这让我很烦恼。
1 个回答
10
你要么从最上面运行你的 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)