Flask request and application/json content type

后端 未结 2 1252
既然无缘
既然无缘 2020-12-13 06:33

I have a flask app with the following view:

@menus.route(\'/\', methods=[\"PUT\", \"POST\"])
def new():
    return jsonify(request.json)

Ho

相关标签:
2条回答
  • 2020-12-13 07:07

    Use request.get_json() and set force to True:

    @menus.route('/', methods=["PUT", "POST"])
    def new():
        return jsonify(request.get_json(force=True))
    

    From the documentation:

    By default this function will only load the json data if the mimetype is application/json but this can be overridden by the force parameter.

    Parameters:

    • force – if set to True the mimetype is ignored.

    For older Flask versions, < 0.10, if you want to be forgiving and allow for JSON, always, you can do the decode yourself, explicitly:

    from flask import json
    
    @menus.route('/', methods=["PUT", "POST"])
    def new():
        return jsonify(json.loads(request.data))
    
    0 讨论(0)
  • 2020-12-13 07:31

    the request object already has a method get_json which can give you the json regardless of the content-type if you execute it with force=True so your code would be something like the following:

    @menus.route('/', methods=["PUT", "POST"])
    def new():
        return jsonify(request.get_json(force=True))
    

    in fact, the flask documentation says that request.get_json should be used instead of request.json: http://flask.pocoo.org/docs/api/?highlight=json#flask.Request.json

    0 讨论(0)
提交回复
热议问题