2

我是 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 的了解的极限(因为我最近几天才开始学习)。我也研究过使用类似的方法将收集到的数据附加到数组中,然后尝试将其放入。

updatepool['properties']['basic']['nodes'].append(add_node)

当我打印更新池时,我看到我所追求的正在工作,但再次将它放入数组中让我感到难过。

任何帮助将非常感激。

谢谢

更新:这是我的代码的更新,从 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)
4

2 回答 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.

您可以提供“dict withlist”(数组)。

于 2014-03-14T10:17:45.170 回答
0

从文档

打印 requests.put。doc 发送 PUT 请求。返回:类: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 接受的密钥 val:假设它接受“节点”和您可以使用的密钥

client.put(url, {'node':add_node}, headers = jsontype) 

或者

client.put(url, {'node':updatepool['properties']['basic']['nodes']**[0]**}, headers = jsontype)

发送第一个节点

于 2014-03-14T10:26:54.517 回答