Python - 更新JSON REST数组
我刚开始学习Python,想写一个脚本,输入一个IP地址,然后更新我从一个JSON RESTful API获取的数组。我可以顺利地从数组中提取数据。以下是我目前的代码(请忽略代码的样子)
import requests
import json
import sys
pool_name = sys.argv[1]
add_node = sys.argv[2]
url = 'https://<stingray RESTApi>:9070/api/tm/1.0/config/active/pools/' + pool_name
jsontype = {'content-type': 'application/json'}
client = requests.Session()
client.auth = ('<username>', '<password>')
client.verify = 0
response = client.get(url)
pools = json.loads(response.content)
nodes = pools['properties']['basic']['nodes']
现在我在考虑使用这个
client.put(url, <I am stuck>, headers = jsontype)
到目前为止,我对Python的了解已经到了瓶颈(因为我刚开始学习几天)。我也考虑过使用类似的东西,把我收集到的数据添加到数组中,然后尝试用PUT方法发送。
updatepool['properties']['basic']['nodes'].append(add_node)
当我打印updatepool时,我看到我想要的效果是实现了,但把它放入数组中的PUT操作让我感到困惑。
任何帮助都会非常感谢。
谢谢
更新:这是我代码的更新,收到了API的400响应
#!/usr/bin/python
import requests
import json
import sys
pool_name = sys.argv[1]
#add_node = sys.argv[2]
add_node = u'10.10.10.1:80'
url = 'https://<uri>:9070/api/tm/1.0/config/active/pools/' + pool_name
jsontype = {'content-type': 'application/json'}
client = requests.Session()
client.auth = ('<username>', '<password')
client.verify = 0
response = client.get(url)
pools = json.loads(response.content)
nodes = pools['properties']['basic']['nodes']
data = nodes
data.append(add_node)
print client.put(url,json.dumps(data), headers=jsontype)
2 个回答
0
根据文档,
put(url, data=None, **kwargs)
Sends a PUT request. Returns Response object.
Parameters:
url – URL for the new Request object.
data – (optional) Dictionary, bytes, or file-like object to send in the body of the Request.
**kwargs – Optional arguments that request takes.
你可以使用包含列表的字典(数组)。
0
来自文档的内容
打印 requests.put.文档 发送一个 PUT 请求。返回一个 :class:
Response
对象。
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
所以 client.put(url, {'key':'value'}, headers = jsontype)
是可以工作的。
现在你需要知道的是那个网址(url)接受什么样的键值对:假设它接受一个叫 'node' 的键,你可以使用
client.put(url, {'node':add_node}, headers = jsontype)
或者
client.put(url, {'node':updatepool['properties']['basic']['nodes']**[0]**}, headers = jsontype)
来发送第一个节点