exceptions returned in HTML break my JSON client. I want to jsonify this output.
More detail: i have a view function which an endpoint of this api app.
As you can see, this function returns the result in json.
@app.route('/route1')
def api_route1():
if user_id in request.args:
k1 = request.args['user_id']
return flask.jsonify(recs=some_function(k1))
else:
return "no valid user_id supplied"
The problem, unhandled exception are in HTML, e.g.,
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>TypeError: 'NoneType' object is not iterable // Werkzeug Debugger</title>
<link rel="stylesheet"
href="?__debugger__=yes&cmd=resource&f=style.css"
type="text/css">
This breaks my json client. The HTML format is clearly a default, but i don't know how to opt out of it and specify jsonified exceptions (and ideally jsonify anything returned even headers).
I suspect what i need is somewhere in the excellent Flask documentation, but i can't find it.
jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.
You should define HTTP error handlers in flask.
A simple JSON returing 404 handler might look something like this:
@app.errorhandler(404)
def page_not_found(e):
return flask.jsonify(error=404, text=str(e)), 404
With this you will be able to check for data.error
on the client and if it exists you can get the error text with data.text (the error passed as e
is werkzeug.exceptions.NotFound
whose string representation is "404: Not Found").
Making the traceback available to the JSON client has the potential to disclose sensitive information.
My advice is:
The 500 page could look like:
{ "error": "500 - internal server error" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With