[英]Python requests library: data vs json named arguments with requests.post
根据requests 库文档的相关部分,将字典传递给 post 方法的主要方法如下:
r = requests.post(url, data = {"example": "request"})
之后,作者演示了将 JSON string 直接传递给 Github ZDB974238703CA8DE634ACE 的示例。 然后作者建议不要将字典编码为 JSON string 并通过data
传递,您可以简单地使用命名参数json
来传递字典,如下所示。
r= requests.post(url, json = {"example": "request"})
你什么时候会使用json
而不是data
? 这种冗余是特殊的还是有意的?
将dict
传递给data
会导致dict
进行表单编码 ,就像您在HTML页面上提交表单一样; 例如, data={"example": "request"}
将作为example=request
在请求体中example=request
。 另一方面, json
关键字将其参数编码为JSON值(并且还将Content-Type
标头设置为application/json
)。
从requests
文档来看, data
似乎是用于表单提交的,因此它被构建为期望dict
数据类型,并且如果可以的话,会将传递给该变量的对象处理为dict
类型。
例如,如果将嵌套的json
传递给data
:
{ "ticker_symbol":ticker, "model_type":"2", "prediction":[ { "epoch_time": 11111100000, "price": 12.00, "confidence_score": 0.6, "rate_of_error": 0.015, }, { "epoch_time": 12112230000, "price": 13.00, "confidence_score": 0.7, "rate_of_error": 0.015, } ] }
它将被“扁平化”成为:
{ "ticker_symbol":ticker, "model_type":"2", "prediction":[ "epoch_time": 11111100000, "price": 12.00, "confidence_score": 0.6, "rate_of_error": 0.015, "epoch_time": 12112230000, "price": 13.00, "confidence_score": 0.7, "rate_of_error": 0.015, ] }
本质上,虽然prediction
被格式化为带有嵌套数据的json
object,但它会被requests.post()
转换为key:[value]
对。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.