在我的网站上,我希望能够为用户提供比“找不到页面”更好的 404 错误反馈。如果 View 引发 404 错误,我想向模板传递一个额外的参数来描述 View 显示的内容。例如:
views.py
def get_or_404(model, attribute, value, template, **kwargs):
try:
return session.query(model).filter(attribute == value).one()
except NoResultFound:
abort(404)
@app.errorhandler(404)
def page_not_found(error):
return render_template("404.html"), 404
@app.route("project/<project_id>")
def project_show(project_id):
"""
Show the files contained in a specific project.
:param int project_id: The ID of the desired project.
"""
project = get_or_404(Project, Project.id, project_id, "item_not_found.html", item="project")
# Other stuff
如果用户尝试访问不存在的项目,则会被发送到 404 页面。如果我可以向模板 404.html
提供 item
kwarg(来自 project_show
),那么模板会显示“Project未找到”而不仅仅是“未找到页面”。
最好的方法是什么?
最佳答案
errorhandler
路线 already has一个 error
参数。当您调用 abort()
时,Flask 会抛出 HTTPException
,而 errorhandler
正在等待该异常。这里的主要思想是,您可以创建自己的异常层次结构或具有不同属性的一个异常,并在您的 errorhandler
模板中使用它。
第二个想法是使用 flashing :出现异常时,闪烁
一条消息并abort()
,然后在您的errorhandler
模板中拾取此消息。
关于python - 将参数传递给 Flask 错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23233111/