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

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 a JSON body request, I just want to parse the json or force Flask to parse it and return request.json.

This is needed because changing the AJAX content type forces an HTTP OPTION request, which complicates the back-end.

How do I make Flask return the raw data in the request object?

 

 

You can get it that way:

@app.route("/path-to-the-post-endpoint", methods=["POST"])
def handle_post_request():
    data = request.form.to_dict()
    data['some_key_1'] = "Some Value 1"
    data['some_key_2'] = "Some Value 2"
    # ...etc.

    # DO SOMETHING HERE

    return [], 200

  

posted @ 2024-04-07 16:22  Oops!#  阅读(7)  评论(0编辑  收藏  举报