Skip to main content
 首页 » 编程设计

python之测试 flask ——避免循环导入

2025年05月04日13qlqwjy

我已经使用 Django 一段时间了,但我决定在我最新的副项目中尝试使用 Flask。因为我不想将整个应用程序放在一个文件中,所以我遵循了文档 here将我的 Flask 应用程序打包。至关重要的是,这些说明引入了一种循环导入:

Every Python programmer hates them, and yet we just added some: circular imports (That’s when two modules depend on each other. In this case views.py depends on __init__.py). Be advised that this is a bad idea in general but here it is actually fine. The reason for this is that we are not actually using the views in __init__.py and just ensuring the module is imported and we are doing that at the bottom of the file.

确实,这还没有在我的应用程序中造成任何问题,如果我删除此行,我的应用程序将无法运行。但是,我的副项目已经足够大了,我决定尝试使用 Flask-Testing 为它编写单元测试。 .在他们所有的文档中,他们只是像往常一样简单地 from package import app ,就像在我的应用程序中的每个子模块中一样。但是,如果我在主包目录中放置一个 tests.py 并尝试导入,然后尝试运行测试,它会因上述循环导入而失败:

File "/home/me/my_app/my_app/__init__.py", line 165, in <module> 
  import views 
File "/home/me/my_app/my_app/views.py", line 23, in <module> 
  from my_app import app, db 
ImportError: cannot import name app 

在 Flask-Testing 的文档中,以及其他地方,如 Mega-Tutorial section on Unit Testing ,此导入已完成并且似乎“正常工作”。然而,对我来说,这是我唯一一次遇到这种循环导入问题。我错过了什么?

请您参考如下方法:

记录在案here你的 my_app/__init__.py 应该是这样的:

from flask import Flask 
 
app = Flask(__name__) 
from my_app import views 

请注意 app 是在 从您的包导入 views 之前定义的。如果您遵循该规则,则不会遇到任何循环导入问题。