【问题标题】:Flask: Blueprint not showing custom error pageFlask:蓝图未显示自定义错误页面
【发布时间】:2020-02-28 03:12:34
【问题描述】:

这是我如何创建一个简单的蓝图

from flask import Blueprint, render_template

my_bp_page = Blueprint('my_bp_page', __name__, template_folder='templates')

@my_bp_page.errorhandler(404)
def page_not_found(e):
    return render_template('404.html', pageName='my_bp_page.home')


@my_bp_page.route('/home', methods=['GET'], strict_slashes=False)
def home():
    return render_template('home.html')

这是我的404.html

{% block title %}Page Not Found{% endblock %}
{% block body %}
  <h1>Page Not Found</h1>
  <p>What you were looking for is just not there.
  <p>
    {% if pageName is defined %}
        <a href="{{ url_for(pageName) }}">Go Back</a>
    {% else %}
        <a href="{{ url_for('home') }}">Go Back</a>
    {% endif %}
{% endblock %}

在测试这个时,我尝试了 URL localhost:5000/home/junk 并且我看到了

Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

这不是我应该看到的。我应该看到我的自定义404.html

我做错了什么?

【问题讨论】:

    标签: python html flask jinja2


    【解决方案1】:

    问题在于,就 Flask 而言,/home/junk 路径不属于您的 my_bp_page 蓝图。它只是一个没有注册路由的路径。

    蓝图文档的 Error Handlers 部分(第 3 段)中提到了此警告。

    推荐的解决方案是使用应用级错误处理程序,并检查 request.path 以自定义处理错误的方式。

    【讨论】:

    • 有道理。我如何为所有404 请求编写一个全局处理程序?我可以在 api 路径/路由中放一些正则表达式吗?
    • 看看我上面链接的页面底部,例子是一个全局错误处理程序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多