Logo Questions Linux Laravel Mysql Ubuntu Git Menu

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

def after_request(response):
    data = response.get_json(silent=True)
    session_id = uuid.uuid4().hex
    if response.status_code == 200 and "results" in data:

            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

like image 338
Jeff Tehrani Avatar asked Dec 06 '22 09:12

Jeff Tehrani

1 Answers

You can also use the make_response method. Just like:

from flask import make_response

def hello():
    data = {'hello': 'world'}
    return make_response(jsonify(data), 403)
like image 126
IkarosKun Avatar answered Dec 26 '22 00:12