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

Flask出现AttributeError: 'Flask' object has no attribute 'get'错误原因排查

Flask AttributeError: 'Flask' object has no attribute 'get' 错误原因解析

错误核心原因

出现这个错误的根本原因是Flask版本过低:

  • @app.get()这类HTTP方法快捷装饰器是Flask 2.0版本才新增的语法糖,用来简化@app.route(path, methods=["GET"])的写法。
  • 如果你当前环境安装的Flask版本低于2.0,Flask对象并没有get这个属性,使用@app.get()就会触发AttributeError。
  • 而@app.route()是Flask从早期版本就支持的标准路由定义方式,通过methods参数指定请求方法,兼容所有Flask版本,因此替换后代码可以正常运行。

原错误代码

from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)

    if test_config is None:
        app.config.from_mapping(
            SECRET_KEY="dev"
        )
    else:
        app.config.from_mapping(test_config)

    @app.get("/")
    def index():
        return "Hello World"

    @app.get("/hello")
    def say_hello():
        return {"message" : "Hellos World"}

    return app

修改后可运行代码

import os
from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)

    if test_config is None:
        app.config.from_mapping(SECRET_KEY=os.environ.get("SECRET_KEY"),)
    else:
        app.config.from_mapping(test_config)

    @app.route('/', methods=["GET"])
    def index():
        return "Hello World"

    @app.route('/hello', methods=["GET"])
    def say_hello():
        return {"message" : "Hellos World"}

    return app

注:修改后的代码需要补充import os,否则os.environ.get会触发未定义错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:01:01