6

In my flask application, I would like to store the response in a MongoDB. I would like to change the status code and response data in case the storing task could not complete. How can I change the status code of Response Object

This is for a Flask application developed in Python 3.6

@after_request() def after_request(response): data = response.get_json(silent=True) session_id = uuid.uuid4().hex if response.status_code == 200 and "results" in data: try: collection = utils.mongodb_connection(db_info) insertion = utils.insert_in_mongo(collection, data["results"], session_id) data["report_id"] = insertion.get("id",None) return jsonify(data) except Exception as e: data["message"] = "Error in storing data" response.status_code = 413 return jsonify(data) 

right now in case of an exception, I receive the status code 200

2

1 Answer 1

17

You can also use the make_response method. Just like:

from flask import make_response @app.route('/') def hello(): data = {'hello': 'world'} return make_response(jsonify(data), 403) 
Sign up to request clarification or add additional context in comments.

5 Comments

I do jsonify(data), 403, directly.
@m3nda That will generates something like: (<Response 99 bytes [200 OK]>, 403) (object length just for example). As you can see the response object has 200 OK set.
Did u check that? I mean, actually I am using jsonify(status="created"), 201 and that never reported 200 as http return code. "Object lenght just for example" tells me that you just guessed it.
Since make_response() implies jsonify, return make_response(data, 403) is enough.
I did @m3nda, Zobayer is right. You are also right, I've checked it with Postman and 403 prevails over jsonify's 200. But try print/log your response before returning like print(jsonify(data)) and you'll see the <Response 90 bytes [200 OK]> thing. You would use print(jsonify(data).__dict__) to see inner details.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.