3

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)
4

1 に答える 1

7

ドキュメントには、ブループリントで 404 エラー ハンドラーが期待どおりに動作しないことが記載されています。アプリはルーティングを処理し、要求がブループリントに到達する前に 404 を発生させます。404 ハンドラーはabort(404)、ブループリント レベルでのルーティング後に発生しているため、引き続きアクティブ化されます。

これは、Flask で修正される可能性があるものです (これについては未解決の問題があります)。回避策として、最上位の 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
于 2015-01-25T17:46:36.070 に答える