无论 Content-Type 标头如何,都可以在 Python Flask 中获取原始 POST 正文 [英] Get raw POST body in Python Flask regardless of Content-Type header
问题描述
之前,我问了如何获取 Flask 请求中收到的数据,因为 request.data
为空.答案解释了 request.data
是原始帖子正文,但如果解析表单数据,它将为空.如何无条件获取原始帖子正文?
Previously, I asked How to get data received in Flask request because request.data
was empty. The answer explained that request.data
is the raw post body, but will be empty if form data is parsed. How can I get the raw post body unconditionally?
@app.route('/', methods=['POST'])
def parse_request():
data = request.data # empty in some cases
# always need raw data here, not parsed form data
推荐答案
使用 request.get_data()
获取原始数据,无论内容类型如何.数据被缓存,随后您可以随意访问request.data
、request.json
、request.form
.
如果您首先访问 request.data
,它会调用 get_data
并带参数首先解析表单数据.如果请求具有表单内容类型(multipart/form-data
、application/x-www-form-urlencoded
或 application/x-url-encoded
) 然后原始数据将被消耗.在这种情况下,request.data
和 request.json
将显示为空.
If you access request.data
first, it will call get_data
with an argument to parse form data first. If the request has a form content type (multipart/form-data
, application/x-www-form-urlencoded
, or application/x-url-encoded
) then the raw data will be consumed. request.data
and request.json
will appear empty in this case.
这篇关于无论 Content-Type 标头如何,都可以在 Python Flask 中获取原始 POST 正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!