Python 蓝图404 errorhandler不';t在blueprint'下激活;s url前缀

Python 蓝图404 errorhandler不';t在blueprint'下激活;s url前缀,python,flask,blueprint,Python,Flask,Blueprint,我用404错误处理程序创建了一个蓝图。但是,当我转到blueprint前缀下不存在的URL时,会显示标准404页面,而不是我的自定义页面。如何使蓝图正确处理404错误 下面是一个演示该问题的简短应用程序。导航到http://localhost:5000/simple/asdf不会显示蓝图的错误页面 #!/usr/local/bin/python # coding: utf-8 from flask import * from config import PORT, HOST, DEBUG s

我用
404
错误处理程序创建了一个蓝图。但是,当我转到blueprint前缀下不存在的URL时,会显示标准404页面,而不是我的自定义页面。如何使蓝图正确处理404错误

下面是一个演示该问题的简短应用程序。导航到
http://localhost:5000/simple/asdf
不会显示蓝图的错误页面

#!/usr/local/bin/python
# coding: utf-8

from flask import *
from config import PORT, HOST, DEBUG

simplepage = Blueprint('simple', __name__, url_prefix='/simple')

@simplepage.route('/')
def simple_root():
    return 'This simple page'

@simplepage.errorhandler(404)
def error_simple(err):
    return 'This simple error 404', err

app = Flask(__name__)
app.config.from_pyfile('config.py')
app.register_blueprint(simplepage)

@app.route('/', methods=['GET'])
def api_get():    
    return render_template('index.html')

if __name__ == '__main__':
    app.run(host=HOST,
            port=PORT,
            debug=DEBUG)
其中提到404错误处理程序将不会像蓝图上预期的那样运行。该应用程序处理路由并在请求到达蓝图之前引发404。404处理程序仍将激活abort(404),因为这是在blueprint级别路由之后发生的

这是一个可能被固定在烧瓶里的东西(它有一个开口)。作为一种解决方法,您可以在顶级404处理程序中执行自己的错误路由

from flask import request, render_template

@app.errorhandler(404)
def handle_404(e):
    path = request.path

    # go through each blueprint to find the prefix that matches the path
    # can't use request.blueprint since the routing didn't match anything
    for bp_name, bp in app.blueprints.items():
        if path.startswith(bp.url_prefix):
            # get the 404 handler registered by the blueprint
            handler = app.error_handler_spec.get(bp_name, {}).get(404)

            if handler is not None:
                # if a handler was found, return it's response
                return handler(e)

    # return a default response
    return render_template('404.html'), 404