Flask - How do I read the raw body in a POST request when the content type is “application/x-www-form-urlencoded”

前端 未结 4 803
既然无缘
既然无缘 2020-12-31 06:23

Turns out that Flask sets request.data to an empty string if the content type of the request is application/x-www-form-urlencoded. Since I\'m using

相关标签:
4条回答
  • 2020-12-31 06:55

    If you want get the JSON when request is 'Content-Type': 'application/x-www-form-urlencoded' you need "force" conversion to json like de code below:

    from flask import Flask, request
    import os
    
    
    app = Flask(__name__)
    
    
    @app.route("/my-endpoint", methods = ['POST'])
    def myEndpoint():
    
        requestJson = request.get_json(force=True)
    
        //TODO: do something....
    
        return requestJson
    
    
    if __name__ == "__main__":
        port = int(os.environ.get('PORT', 5000))
        app.run(host='0.0.0.0', port=port, debug=True, use_reloader=True)
    
    0 讨论(0)
  • 2020-12-31 07:12

    Use request.get_data() to get the POST data. This works independent of whether the data has content type application/x-www-form-urlencoded or application/octet-stream.

    0 讨论(0)
  • 2020-12-31 07:15

    You can get the post data via request.form.keys()[0] if content type is application/x-www-form-urlencoded.

    request.form is a multidict, whose keys contain the parsed post data.

    0 讨论(0)
  • 2020-12-31 07:19

    try this:

    f = request.form
    
       output = []
    
       user_data = {}
    
       user_data['email'] = f['email']
    
       user_data['password'] = f['password']
    
       user_data['key'] = f['key']
    
       output.append(user_data)
    
    0 讨论(0)
提交回复
热议问题