【问题标题】:Blueprint 404 errorhandler doesn't activate under blueprint's url prefix蓝图 404 错误处理程序未在蓝图的 url 前缀下激活
【发布时间】:2015-01-25 14:25:36
【问题描述】:

我创建了一个带有404 错误处理程序的蓝图。但是,当我转到蓝图前缀下不存在的 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)

【问题讨论】:

    标签: python flask blueprint


    【解决方案1】:

    documentation 提到 404 错误处理程序在蓝图上的行为将不符合预期。该应用程序处理路由并在请求到达蓝图之前引发 404。 404 处理程序仍会为 abort(404) 激活,因为这是在蓝图级别路由之后发生的。

    这可能会在 Flask 中得到解决(有一个公开的issue 关于它)。作为一种解决方法,您可以在顶级 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 2011-05-01
      相关资源
      最近更新 更多