如何在Flask蓝图中引用主文件main.py里定义的方法?
解决Flask Blueprint引用main.py中方法的问题
最优方案:抽离公共方法到独立模块
直接在main.py和Blueprint之间互相导入容易触发循环导入(main要注册Blueprint,Blueprint又导入main),最规范的做法是把通用方法抽离到单独的工具模块:
- 在
mainfolder下新建utils.py文件,将checkIt()方法移到这里:
# utils.py def checkIt(): # 原checkIt的实现逻辑 print("执行checkIt方法")
- 在
main.py中导入并使用该方法:
# main.py from flask import Flask from blueprints.blueprint1.blueprint1 import bp1 from utils import checkIt app = Flask(__name__) app.register_blueprint(bp1) # 调用checkIt checkIt() if __name__ == "__main__": app.run()
- 在
blueprint1.py中同样导入使用:
# blueprints/blueprint1/blueprint1.py from flask import Blueprint from utils import checkIt bp1 = Blueprint('bp1', __name__) @bp1.route('/test') def test_route(): # 调用checkIt方法 checkIt() return "调用checkIt成功"
临时方案:延迟导入(避免循环导入)
如果暂时不想抽离方法,可以在Blueprint的视图函数内部导入main.py的checkIt(),而不是在文件顶部导入:
# blueprints/blueprint1/blueprint1.py from flask import Blueprint bp1 = Blueprint('bp1', __name__) @bp1.route('/test') def test_route(): # 在函数内部延迟导入,避免循环导入 from main import checkIt checkIt() return "调用checkIt成功"
这种方式可以绕过循环导入问题,但长期来看,还是抽离到工具模块更利于代码维护。
内容的提问来源于stack exchange,提问作者MW_DEVEL
相关产品推荐
相关产品推荐

