【问题标题】:How to check if a custom error message is thrown by abort() in Flask?如何检查 Flask 中的 abort() 是否抛出自定义错误消息?
【发布时间】:2019-05-03 12:18:48
【问题描述】:

我正在使用 Flask 创建一个简单的网络应用程序。对于某些视图,如果某些条件不匹配,我会抛出 403 错误:

@admin.route("/employees/assign/<int:id>", methods=["GET", "POST"])
@login_required
def assign_employee(id):
    """Assign a department and a role to an employee."""
    check_admin()

    employee = Employee.query.get_or_404(id)

    if employee.is_admin:
        abort(403,f"You're not permitted to edit {employee.first_name}'s role and department.")

    do_something()
    return render_template(a_template)

为了处理这些错误,我还在我的主初始化文件中添加了错误处理程序。

@app.errorhandler(403)
def fordbidden(error):
    return (
        render_template(
            "errors/403.html", title="Forbidden", error_message=error.description
        ),
        403,
    )

最后,我在我的 Jinja 模板中显示错误描述:

<div style="text-align: center">
    <h1> 403 Error </h1>
    {% if error_message %}
        <h3> {{error_message}} </h3>
    {% else %}
        <h3>You're not authorised to access this ressource.</h3>
    {% endif %}
    <hr class="intro-divider">
    <a href="{{ url_for('home.homepage') }}" class="btn btn-default btn-lg">
        <i class="fa fa-home"></i>
        Home
    </a>
</div>

我想做的是显示自定义错误消息当且仅当有一个,否则使用我的模板中定义的标准消息。但是,我的{% if error_message %} 似乎总是正确的,因为默认情况下错误总是传递一条消息。

有没有办法检查是否存在自定义错误消息?

【问题讨论】:

    标签: python-3.x flask error-handling jinja2 wsgi


    【解决方案1】:

    可以使用jinja2自带的默认过滤器:

    您可以将 if-else 结构替换为以下内容:

    <h3>{{error_message|default(“You're not authorised to access this resource.“‚true)}}</h3>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 2016-05-14
      • 1970-01-01
      • 2018-01-08
      • 2014-05-03
      相关资源
      最近更新 更多