KeyError: <weakref at 0x0000018692731350; to 'Flask' at 0x000001869149A8D0>

我在学flask的时候遇到奇怪问题,先来一段代码:

@indexRoute.route('/')
def page_index():
    return render_template("index.html")

以上代码运行正常,之后代码修改如下:

@indexRoute.route('/')
def page_index():
    photos = DBphotos()
    result = photos.get_data()
    return render_template("index.html", result=result)

修改后出现错误:
KeyError: <weakref at 0x0000018692731350; to ‘Flask’ at 0x000001869149A8D0>
开始我以为是get_data()有问题,几经调试,把代码放在def外,直接用:

photos = DBphotos()
result = photos.get_data()
print(result)

结果又正常运行。

网上查了很多资料都不对,请高手看看问题发生在哪里?谢谢

讨论数量: 6
@indexRoute.route('/')
def page_index():
    try:
        photos = DBphotos()
        result = photos.get_data()
        return render_template("index.html", result=result)
    except Exception as e:
        print(e)
        return render_template("index.html")
2年前 评论
thinkdogo (楼主) 2年前

看下你的模板文件,有没有传入 result 这个参数。

2年前 评论
thinkdogo (楼主) 2年前
hustnzj (作者) 2年前

我尝试把 app.py 中的

from controller.index import *
app.register_blueprint(indexRoute)

放在if __name__ == '__main__':之外,问题居然解决了

但我还是搞不清原理,我试过手动赋值给变量result,运行是正常的,模板页面也能正常打印result的值, 我想如果Blueprint出问题的话,即使我手动赋值也应该出错。 不管怎样,还是非常感谢版主@hustnzj

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!