You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask报错NameError: name 'app' is not defined 求助

问题原因

你在main.py的index函数里直接使用app变量,但这个变量仅在__init__.py的create_app()函数内部定义,属于局部变量,main模块无法直接访问到它,所以会出现未定义的错误。

解决方案

Flask提供了current_app对象,它会在请求上下文自动指向当前运行的Flask应用实例,这是访问应用配置的标准方式。修改main.py代码如下:

from flask import Blueprint, render_template, current_app

main = Blueprint('main', __name__)

@main.route('/')
def index():
    print(current_app.config['CUSTOM_VARIABLE'])
    return render_template('index.html')
补充说明
  • current_app只能在请求上下文或应用上下文存在时使用,在视图函数里使用完全没问题,因为视图函数触发时已经处于请求上下文中。
  • 不要尝试直接从__init__.py导入app,因为app是create_app()的返回值,不是全局变量,这种导入方式会导致循环导入或者获取到未初始化的实例。

内容的提问来源于stack exchange,提问作者Anthony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 06:52:01