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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With