简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM