繁体   English   中英

Python 请求库:数据与 json 命名为 arguments 与 requests.post

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM