如何检查 Flask 中的 abort() 是否抛出自定义错误消息?

How to check if a custom error message is thrown by abort() in Flask?

我正在使用 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 %} 永远是真的,因为错误总是默认传递一条消息。

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

你可以使用jinja2内置的默认过滤器:

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

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