Python传递变量

Python传递变量,python,python-2.7,Python,Python 2.7,我试图弄明白为什么我不能传递我的两个变量来让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 w

我试图弄明白为什么我不能传递我的两个变量来让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()

您应该使用json模块将Python dict(头)转换为json对象。虽然它们相似,但语法却有细微的不同

我在这里看到的另一个问题是,在测试服务器时,
server
是未定义的。您在
for
循环中创建了
server
,但是如果节点==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

循环逻辑不正确,因为它迭代字典,但始终保留最后一个k,v对

servers = {'server1.com':'#######','server2.com':'######'}
for server, key in servers.items():
    print server
这基本上意味着每次运行时,它都会保留来自dict的相同值。您不应该在循环之外使用
server/key
变量,这是不对的,您可能会遇到奇怪的行为

但问题在于你的dict检索

if node == server:
    **print serves.item(server)** # there's a typo here
    print servers.item(key)
    box = servers.item(server)
    api = servers.item(key)
如果要从dict获取密钥值,请使用
servers.get(server)
servers[server]


我不知道为什么要检查node==server?您可以消除这一点,只需直接从服务器请求节点dict:
box=servers.get(node)
print services.item(server)
这会返回什么?如果是
服务器的打字错误
下一行的问题相同
dict
没有项函数…我获得了要查看和选择的初始字典列表,但在我选择之后,它不会打印任何内容,并以错误代码0退出。定义了api的服务器是一个未定义的错误。节点所在的位置应为end of语句。我需要缩进吗?谢谢,我已经移动了它,现在我得到了api密钥,但之后就没有了。节点名和api键是如何翻转的?这是因为节点是您的键。尝试使用
node
而不是box,并且
api=servers.get(node)
应该可以工作