Search code examples
pythonflaskflask-restful

Flask: How to change status code using jsonify to return Response?


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


Solution

  • 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)