我试图找出为什么我无法传递我的两个变量以使API调用起作用。我知道当我在其位置放置静态名称/密钥时,API调用有效。 任何帮助,将不胜感激。
import httplib
#Print my list to choose from.
servers = {'server1.com':'#######','server2.com':'######'}
for server, key in servers.items():
print server
#User chooses which node, it should print what they chose, then store into
variable to send for API Post.
node = raw_input("Which node would you like to check Network Bytes for? ")
if node == server:
print serves.item(server)
print servers.item(key)
box = servers.item(server)
api = servers.item(key)
headers = {'Content-Type': 'application/json', 'Accept': 'application/json',
'Authorization': 'GetData apikey=' + api}
body = r"""{
"cycle": "5min",
"from": 0,
"metric_category": "net",
"metric_specs": [
{
"name": "bytes_in"
}
],
"object_ids": [
0
],
"object_type": "device",
"until": 0
}
"""
conn = httplib.HTTPSConnection(box)
conn.request('POST', '/api/v1/metrics', headers=headers, body=body)
resp = conn.getresponse()
print resp.read()
答案 0 :(得分:0)
您应该使用json模块将Python dict(标头)转换为json对象。虽然它们相似但语法略有不同。
我在这里看到的另一个问题是,当你测试它时,server
是未定义的。您在server
循环中创建了for
,但在if node == server:
之前它已超出范围。也许您可以用以下内容替换该部分:
#User chooses which node, it should print what they chose, then store into
variable to send for API Post.
box = raw_input("Which node would you like to check Network Bytes for? ")
api = servers.get(node, None):
print "box/node:", box
print " api :", api
答案 1 :(得分:0)
你的循环逻辑不正确,因为它迭代字典但总是保留最后一个k,v对。
servers = {'server1.com':'#######','server2.com':'######'}
for server, key in servers.items():
print server
这基本上意味着每次运行时,它将从dict中保持相同的值。你不应该在你的循环之外使用server / key
变量,它不对,你可能会发现奇怪的行为
但问题在于您的字典检索
if node == server:
**print serves.item(server)** # there's a typo here
print servers.item(key)
box = servers.item(server)
api = servers.item(key)
如果您想从字典中获取密钥的值,请使用servers.get(server)
或servers[server]
。
我不确定你为什么要查看if node == server
?您可以消除它,只需直接从服务器dict:box = servers.get(node)