Reputation: 19325
I'm (attempting) to create a RESTlike API via Flask and would like to include the HTTP response code inside the returned json response. I've found the flask.jsonify()
very helpful in generating my responses and I can manipulate the response via the app.after_request
decorator.
The issue I have is that the response data is already serialized by the time I can read it in the function I decorate with app.after_request
so to insert the response.status_code
would require de-serializing and re-serializing every request.
I'm very new to flask and am unsure of the 'correct' way to get the status_code into the response, preferably before it gets serialized into a completed response.
Upvotes: 1
Views: 1473
Reputation: 67489
I never needed to do something like this myself, but you can probably do this by subclassing the Response
class.
Let's say you create a JSONResponse
class as a subclass of Response
. The constructor of this class takes the same arguments as the parent class, but instead of a string for the body it takes a dictionary.
So you do not call jsonify()
at this point, just pass the dictionary with the data into the JSONResponse
object. The response object takes the dictionary and stores it aside in a member variable, and then calls the parent response class and sets an empty response body for now.
I think this will fool Flask into thinking the response is valid.
When you get to the after_request
handler you have access to the response object, so you can get the dictionary, still in its native form, and make any modifications you want.
The JSONResponse
class has a method that is called, say, render()
that you call when you are done modifying the dictionary. This method calls jsonify()
on the final version of the data and updates the response body in the parent class.
Upvotes: 1