The request's content-type
is application/json
, but I want to get the request body bytes. Flask will auto convert the data to json
. How do I get the request body?
You can get the non-form-related data by calling request.get_data()
You can get the parsed form data by accessing request.form
and request.files
.
However, the order in which you access these two will change what is returned from get_data
. If you call it first, it will contain the full request body, including the raw form data. If you call it second, it will typically be empty, and form
will be populated. If you want consistent behavior, call request.get_data(parse_form_data=True)
.
You can get the body parsed as JSON by using request.get_json()
, but this does not happen automatically like your question suggests.
See the docs on dealing with request data for more information.
If you want the data as a string instead of bytes, use request.get_data(as_text=True)
. This will only work if the body is actually text, not binary, data.
要流式传输数据而不是一次读取所有数据,请访问request.stream
。
Files in a FormData request can be accessed at request.files
then you can select the file you included in the FormData eg request.files['audio']
.
So now if you want to access the actual bytes of the file, in our case 'audio' using .stream
, you should make sure first that your cursor points to the first byte and not to the end of the file, in which case you will get empty bytes.
Hence, a good way to do it:
file = request.files['audio']
file.stream.seek(0)
audio = file.read()
如果数据是 JSON,使用request.get_json()
来解析它。
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.