5

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

Jeff Tehrani
  • 185
  • 1
  • 3
  • 8
  • Possible duplicate of [Flask: Sending data and status code through a Response object](https://stackoverflow.com/questions/45412228/flask-sending-data-and-status-code-through-a-response-object) – Christopher Peisert Aug 26 '19 at 21:42
  • This is a completely different question since after_request won't let the user to Identify the status by `return jsonify(data) , 403` – Jeff Tehrani Aug 27 '19 at 14:54

1 Answers1

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)
andilabs
  • 22,159
  • 14
  • 114
  • 151
IkarosKun
  • 463
  • 3
  • 15
  • 1
    I do `jsonify(data), 403`, directly. – m3nda Dec 21 '20 at 19:17
  • 1
    @m3nda That will generates something like: `(, 403)` (object length just for example). As you can see the response object has 200 OK set. – Zobayer Hasan Jul 06 '21 at 16:05
  • 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. – m3nda Jul 06 '21 at 19:08
  • Since `make_response()` implies jsonify, `return make_response(data, 403)` is enough. – Mauricio Sep 02 '21 at 20:54
  • 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 `` thing. You would use `print(jsonify(data).__dict__)` to see inner details. – Mauricio Sep 02 '21 at 21:05