问题描述
请求的 content-type
是 application/json
,但是我想获取请求正文字节.Flask会自动将数据转换为 json
.如何获得请求正文?
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?
推荐答案
您可以通过调用 request.get_data()
您可以通过访问 request.form
和 request.files
.
但是,访问这两个命令的顺序将更改从 get_data
返回的内容.如果先调用它,它将包含完整的请求正文,包括原始表单数据.如果您第二次调用它,它通常是空的,并且将填充 form
.如果您想要一致的行为,请调用 request.get_data(parse_form_data = True)
.
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)
.
您可以使用 request.get_json()
将正文解析为JSON,但这不会像您的问题所建议的那样自动发生.
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.
这篇关于如何在Flask中获取请求正文字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!