无论Content-Type标题如何,都可以在Python Flask中获取原始的POST正文 [英] Get raw POST body in Python Flask regardless of Content-Type header

查看:2030
本文介绍了无论Content-Type标题如何,都可以在Python Flask中获取原始的POST正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前,我询问了如何获取Flask请求中收到的数据,因为 request.data 是空的。答案解释说, request.data 是原始文章主体,但是如果表单数据被分析,将是空的。

  @ app.route('/',methods = ['POST'] )
def parse_request():
data = request.data#在某些情况下为空
#在这里总是需要原始数据,而不是解析数据


解决方案

使用 request.get_data() 获取原始数据,而不管内容类型。数据被缓存,随后可以访问 request.data request.json 请求如果你先访问 request.data ,它将会自动完成。 调用带有参数的 get_data 来首先解析表单数据。如果请求具有表单内容类型( multipart / form-data application / x-www-form-urlencoded ,或 application / x-url-encoded ),那么原始数据将被消耗。 request.data request.json 在这种情况下将显示为空。


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

解决方案

Use request.get_data() to get the raw data, regardless of content type. The data is cached and you can subsequently access request.data, request.json, request.form at will.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆