python - 将参数传递给 Flask 错误处理程序

标签 python flask

在我的网站上,我希望能够为用户提供比“找不到页面”更好的 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/

相关文章:

来自文件的Python嵌套循环

python - 使用自定义错误处理程序时如何从中止命令访问错误消息

python - 错误信息 : argument of type 'type' is not iterable

python - Python 中的 only() 方法?

python - 使用 python 和 twitterApi 将多个图像添加到推文?

python - 如何测试 SocketIO 服务器连接(使用 pytest 或任何其他包)?

python - 你如何为 Flask 安装 MySQL?

python - 'MyClass' 对象没有属性 '__getitem__'

python - 同一蓝图中允许多个子域

javascript - 为什么我的 WebSocket 使用 Flask 自动关闭?