python Flask -当内容类型为“application/x-www-form-urlencoded”时,如何读取POST请求中的原始主体

pn9klfpd  于 2023-02-07  发布在  Python
关注(0)|答案(6)|浏览(381)

如果请求的内容类型是application/x-www-form-urlencoded,Flask会将request.data设置为空字符串,因为我使用的是JSON主体请求,所以我只想解析json或强制Flask解析它并返回request.json
这是必需的,因为更改 AJAX 内容类型会强制HTTP OPTION请求,这会使后端变得复杂。
如何让Flask返回request对象中的原始数据?

1cosmwyk

1cosmwyk1#

如果内容类型为application/x-www-form-urlencoded,则可以通过request.form.keys()[0]获取帖子数据。
request.form是多字节,其键包含解析后的post数据。

7vux5j2d

7vux5j2d2#

使用request.get_data()获取POST数据。这与数据的内容类型是application/x-www-form-urlencoded还是application/octet-stream无关。

2sbarzqh

2sbarzqh3#

如果要在请求为“Content-Type”时获取JSON:'application/x-www-form-urlencoded'您需要“强制”转换为json,如以下代码所示:

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)
vlju58qv

vlju58qv4#

main.py

import json

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['POST'])
def index():
    mimetype = request.mimetype
    if mimetype == 'application/x-www-form-urlencoded':
        form = json.loads(next(iter(request.form.keys())))
    elif mimetype == 'multipart/form-data':
        form = dict(request.form)
    elif mimetype == 'application/json':
        form = request.json
    else:
        form = request.data.decode()
    print(mimetype, form, type(form))
    return form

if __name__ == '__main__':
    app.run()

试验

curl -X POST http://127.0.0.1:5000/ --data "{\"a\":1, \"b\":2}"

curl -X POST http://127.0.0.1:5000/ -F a=1 -F b=2

curl -X POST -H "Content-type: application/json" http://127.0.0.1:5000/ --data "{\"a\":1, \"b\":2}"

结果

application/x-www-form-urlencoded {'a': 1, 'b': 2} <class 'dict'>
multipart/form-data {'a': '1', 'b': '2'} <class 'dict'>
application/json {'a': 1, 'b': 2} <class 'dict'>
xxe27gdn

xxe27gdn5#

试试这个:

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)
vjrehmav

vjrehmav6#

你可以这样理解:

@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

相关问题