我的 flask 应用程序具有以下结构。当无效的 url 出现时,会调用 404 错误,但我的 404.html 需要来自 context_processor 的数据,但在中止 404 中,蓝图为 None,因此永远不会调用 context_processor 并且 404.html 丢失数据。
我该如何以不同的方式处理这个问题?
init.py
def create_app(settings_overide=None):
app = factory.create_app(__name__, __path__, settings_overide)
if not app.debug:
app.errorhandler(404)(page_not_found)
return app
def page_not_found(e):
return render_template('404.html'), 404
处理器.py
@blueprint.context_processor
def load_global_data():
return get_data()
最佳答案
当没有找到路线时,还没有设置蓝图(因为设置蓝图需要先确定路线)。因此,404 错误处理程序不能指望蓝图已确定。
您必须手动执行 get_data()
调用。测试是否已设置特定的全局变量,如果未设置,则在渲染 404 模板之前执行 get_data()
函数。
关于python - 404 错误处理程序中缺少 Flask 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555768/