Flask和错误处理BadRequest异常

时间:2016-06-14 14:17:50

标签: python flask

我有这样简单的观点:

@blueprint.route('/')
def index():
    '''CMS splash page!'''
    print request.form['no-key-like-that']

    return render_template('home/splash.html', title='Welcome')

该视图的目标是在Flask上导致BadRequest错误。这种情况发生了,我在这个过程中得到了非常通用的错误页面:

Bad Request

The browser (or proxy) sent a request that this server could not understand.

但是我想拦截所有错误并将它们包含在我们的模板中以获得更好的外观和感觉,我这样做:

@app.errorhandler(TimeoutException)
def handle_timeout(error):
    if utils.misc.request_is_xhr(request):
        return jsonify({'api_timeout': True}), 503

    return redirect(url_for('errors.api_timeout', path=request.path))

然而,对于BadRequest异常不能做同样的事情,我试过:

@app.errorhandler(werkzeug.exceptions.BadRequestError)
def handle_bad_request(error):
    return render_template(
        'errors/bad_request.html',
        exception_message=unicode(error),
        return_path=request.path), 400

@app.errorhandler(werkzeug.exceptions.BadRequestKeyError)
def handle_bad_request(error):
    return render_template(
        'errors/bad_request.html',
        exception_message=unicode(error),
        return_path=request.path), 400

@app.errorhandler(werkzeug.exceptions.HttpError)
def handle_bad_request(error):
    return render_template(
        'errors/bad_request.html',
        exception_message=unicode(error),
        return_path=request.path), 400

在每种情况下,我都会提到上面提到的原始响应,而不是我的bad_request.html。

Bad Request

The browser (or proxy) sent a request that this server could not understand.

实际上对我有用:

# NOTE: for some reason we cannot intercpet BadRequestKeyError, didn't
# figure out why. Thus I have added check if given 400 is
# BadRequestKeyError if so display standard api error page. This happens
# often when dev tries to access request.form that does not exist.
@app.errorhandler(400)
def handle_bad_request(error):
    if isinstance(error, werkzeug.exceptions.BadRequestKeyError):
        if utils.misc.request_is_xhr(request):
            return jsonify({
                'api_internal_error': True,
                'error': unicode(error)
            }), 500

        return render_template(
            'errors/api_internal.html',
            exception_message=unicode(error),
            return_path=request.path), 500

然而,你可以看到它远非完美,因为错误400不一定总是BadRequestKeyError。

因为异常处理适用于任何其他异常但不适用于BadRequest系列,它让我感到疑惑,这是一个错误吗?或许我做错了。

0 个答案:

没有答案