`redirect` calls are not caught by `handle_http_exception` while RequestRedirect is.
I'm using Flask to implement an app that returns JSON for most requests including error responses for bad requests, page not found, etc.
To do this I wrapped the default handle_http_exception method of the app similar to how it was handled in the Flask_exceptional module https://github.com/jzempel/flask-exceptional/blob/master/flask_exceptional.py so that I could return the Response as JSON rather than the default generated HTML.
What I found was that any views that used the Flask redirect function rendered the redirect as HTML. However, if you add a route which ends with a slash, Werkzeug's routing code will automatically fire off a RequestRedirect which would get caught by the handle_http_exception and rendered as JSON.
Do you have a test case for this>
Here is a test app I just threw together to illustrate the problem:
from functools import wraps
from flask import Flask, redirect, jsonify
app = Flask(__name__)
def get_http_exception_handler(app):
"""Overrides the default http exception handler to return JSON."""
handle_http_exception = app.handle_http_exception
@wraps(handle_http_exception)
def ret_val(exception):
exc = handle_http_exception(exception)
# Returning directly as below results in missing Location header
# on 301 errors which is useful for this test as it will fail to
# redirect.
return jsonify({'code':exc.code, 'message':exc.message}), exc.code
return ret_val
# Override the HTTP exception handler.
app.handle_http_exception = get_http_exception_handler(app)
# This route is here as a route to get redirected to on a successful
# redirect.
@app.route("/")
def hello():
return "Hello World!"
# The following route will do a redirect to / if you go to
# http://localhost/redirect/ but if you go to
# http://localhost/redirect you will hit the exception handler
# and get a JSON message instead as it tries to redirect you
# to http://localhost/redirect/.
@app.route("/redirect/")
def test_redirect():
return redirect("/")
if __name__ == "__main__":
app.run()
Not much we can do here. You need to make your handler smarter, so it copies the headers too, if that's what you need. I'd just add a handler for RequestRedirect that passes it through, and add another handler for all other HTTPExceptions instead of trying to override handle_http_exception.
@app.errorhandler(RequestRedirect)
def handle_redirect(e):
return e
@app.errorhandler(HTTPException)
def handle_error(e):
return 'bad', 500