I'm using the exception mapping from mimerender (let's take the json as example), however the output is different than when a request is working:
import json
import mimerender
...
mimerender = mimerender.FlaskMimeRender()
render_xml = lambda message: '<message>%s</message>'%message
render_json = lambda **args: json.dumps(args)
render_html = lambda message: '<html><body>%s</body></html>'%message
render_txt = lambda message: message
render_xml_exception = lambda exception: '<exception>%s</exception>'%exception
render_json_exception = lambda exception: json.dumps(exception.args)
render_html_exception = lambda exception: '<html><body>%s</body></html>'%exception
render_txt_exception = lambda exception: exception
@mimerender.map_exceptions(
mapping=(
(ValueError, '500 Internal Server Error'),
(NotFound, '404 Not Found'),
),
default = 'json',
html = render_html_exception,
xml = render_xml_exception,
json = render_json_exception,
txt = render_txt_exception
)
@mimerender(
default = 'json',
html = render_html,
xml = render_xml,
json = render_json,
txt = render_txt
)
def test(...
When a request works i get this response:
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: application/json
< Content-Length: 29
< Vary: Accept
< Server: Werkzeug/0.8.3 Python/2.7.3rc2
< Date: Tue, 20 Nov 2012 19:27:30 GMT
<
* Closing connection #0
{"message": "Success"}
When a request fails and an exception is triggered:
* HTTP 1.0, assume close after body
< HTTP/1.0 401 Not Found
< Content-Type: application/json
< Content-Length: 25
< Vary: Accept
< Server: Werkzeug/0.8.3 Python/2.7.3rc2
< Date: Tue, 20 Nov 2012 19:16:45 GMT
<
* Closing connection #0
["Not found"]
My question: With the exception I want the same kind of output so like this:
{'message': 'Not found'}
How can this be achieved?
Clearly exception.args is a list, and it is being returned as such :-) To change this, simply change the datastructure you are returning.
In other words, change:
render_json_exception = lambda exception: json.dumps(exception.args)
to:
render_json_exception = lambda exception: json.dumps({"message": exception.args})
Or, if you must return only one message on error:
render_json_exception = lambda exception: json.dumps({"message": " - ".join(exception.args)})
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