Python等价于将POST有效负载包装在单引号中

时间:2019-02-01 21:43:13

标签: python json splunk

与Splunk相比,这更像是一个python问题,但是如果有人这样做的话会有所帮助...特别是here,这里讨论了在单个POST中将多个指标发送到服务器。他们提供的示例是使用curl并将整个有效负载包装在单引号(')中,例如

curl -k http://<IP address or host name or load balancer name>:8088/services/collector  \
-H "Authorization: Splunk 98a1e071-bc35-410b-8642-78ce7d829083"                         
\
-d '{"time": 1505501013.000,"source":"disk","host":"host_99","fields": 
{"region":"us-west-1","datacenter":"us-west- 1a","rack":"63","os":"Ubuntu16.10","arch":"x64","team":"LON","service":"6","service_version":"0","service_environment":"test","path":"/dev/sda1","fstype":"ext3","_value":999311222774,"metric_name":"total"}}
{"time": 1505511013.000,"source":"disk","host":"host_99","fields": 
{"region":"us-west-1","datacenter":"us-west-1a","rack":"63","os":"Ubuntu16.10","arch":"x64","team":"LON","service":"6","service_version":"0","service_environment":"test","path":"/dev/sda1","fstype":"ext3","_value":1099511627776,"metric_name":"total"}}'

我的问题是如何在python中做同样的事情-也就是说,您不能像curl命令中那样将多个JSON对象用单引号引起来-这只会使整个有效负载成为字符串。还有其他包装可以用于此目的吗?

所以,这可行:

payload = {"time": 1505501013.000,"source":"disk","host":"host_99","fields": 
{"region":"us-west-1","datacenter":"us-west- 1a","rack":"63","os":"Ubuntu16.10","arch":"x64","team":"LON","service":"6","service_version":"0","service_environment":"test","path":"/dev/sda1","fstype":"ext3","_value":999311222774,"metric_name":"total"}}

但这不是:

payload = {"time": 1505501013.000,"source":"disk","host":"host_99","fields": 
{"region":"us-west-1","datacenter":"us-west- 1a","rack":"63","os":"Ubuntu16.10","arch":"x64","team":"LON","service":"6","service_version":"0","service_environment":"test","path":"/dev/sda1","fstype":"ext3","_value":999311222774,"metric_name":"total"}}
 {"time": 1505511013.000,"source":"disk","host":"host_99","fields": 
{"region":"us-west-1","datacenter":"us-west-1a","rack":"63","os":"Ubuntu16.10","arch":"x64","team":"LON","service":"6","service_version":"0","service_environment":"test","path":"/dev/sda1","fstype":"ext3","_value":1099511627776,"metric_name":"total"}}

仅供参考,然后POST如下:

 resp = requests.post(splunkurl,json=payload,headers=headers)

1 个答案:

答案 0 :(得分:4)

好吧,“多个json对象”在它是对象的列表之前不是有效的json。

通常,python不在乎(就像其他任何网络工具一样),json只是数据格式,您需要使用其他格式。因此,您需要自己构造文本有效载荷,即OrderBy(),然后通过网络客户端将其作为“原始”数据发送。

我非常怀疑主流http库是否提供了这样的用例。


不确定拒绝的原因,即requests库(对于高级网络来说是一种标准的事实)具有有效处理有效载荷的功能:

json.dumps(payload1) + json.dumps(payload2)

Json与http本身无关,它只是序列化数据的一种方法。大多数客户最终都将使用requests.post(url, data={'v1': 1, 'v2': 2}) # will encode it as form data requests.post(url, json={'v1': 1, 'v2': 2}) # will encode as json requests.post(url, data="{'v1': 1}{'v2': 2}") # will send as-is ,这根本不在乎,唯一的问题是库是否提供了一种简单的方式来发送原始数据