Blueprint 404错误处理程序不会在蓝图的网址前缀下激活 [英] Blueprint 404 errorhandler doesn't activate under blueprint's url prefix

查看:252
本文介绍了Blueprint 404错误处理程序不会在蓝图的网址前缀下激活的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 404 错误处理程序创建了蓝图。但是,当我转到不存在的蓝图前缀下的URL时,将显示标准的404页面而不是我自定义的页面。我怎样才能使蓝图正确地处理404错误?



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



<$ p $来自烧瓶导入的

$编码:utf-8

$配置导入的
PORT,HOST ,DEBUG
$ b 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
$ b $ app = Flask(__ name__)
app.config.from_pyfile('config.py')
app.register_blueprint(简单页)

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

if __name__ == '__main__':
app.run(host = HOST,
port = PORT,
debug = DEBUG)


解决方案

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



这是可以在Flask中解决的问题(有关此问题的开放问题)。作为一种解决方法,您可以在顶级404处理程序中执行自己的错误路由。

  from flask import request,render_template 

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

#通过每个蓝图查找前缀匹配路径
#不能使用request.blueprint,因为路由不匹配任何内容
用于bp_name,bp在app.blueprints.items()中:
如果path.startswith bp.url_prefix):
#获取由蓝图注册的404处理程序
handler = app.error_handler_spec.get(bp_name,{}).get(404)

不是None:
#如果找到一个处理程序,返回它的响应
返回处理程序(e)

#返回一个默认响应
返回render_template('404。 html'),404


I created a blueprint with a 404 error handler. However, when I go to non-existent urls under the blueprint's prefix, the standard 404 page is shown rather than my custom one. How can I make the blueprint handle 404 errors correctly?

The following is a short app that demonstrates the problem. Navigating to http://localhost:5000/simple/asdf will not show the blueprint's error page.

#!/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)

解决方案

The documentation mentions that 404 error handlers will not behave as expected on blueprints. The app handles routing and raises a 404 before the request gets to the blueprint. The 404 handler will still activate for abort(404) because that is happening after routing at the blueprint level.

This is something that could possibly be fixed in Flask (there's an open issue about it). As a workaround, you can do your own error routing within the top-level 404 handler.

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

这篇关于Blueprint 404错误处理程序不会在蓝图的网址前缀下激活的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆