python如何将变量放入命令字符串

时间:2018-01-26 19:47:34

标签: python json

我是python的新手,无法弄清楚如何执行以下操作。 我想在命令中放一个变量,但它不起作用。该命令采用变量名而不是其值。

下面的脚本使用用户名和密码调用https来获取令牌。我退回了令牌。然后我需要使用令牌来创建用户。 我遇到了问题,iplanet对中的“token”没有正确扩展。它设置正确,因为我可以在命令之前将其打印出来。因此令牌将包含类似“AQIC5wM2LY4Sfcydd5smOKSGJT”的内容,但是当进行第二次http调用时,它会传递单词令牌而不是令牌值。

    import requests
    import json

    url = "https://www.redacted.com:443/json/authenticate"

    headers = {
        'X-Username': "user",
        'X-Password': "password",
        'Cache-Control': "no-cache",
        }

    response = requests.request("POST", url, headers=headers)

    tokencreate = json.loads(response.text)
    token=tokencreate['tokenId']
    print token

    url = "https://www.redacted.com:443/json/users"

    querystring = {"_action":"create"}

    payload = "{\r\n\"username\":\"Patrick\",\r\n\"userpassword\":\"{{userpassword}}\",\r\n\"mail\":\"patrick@example.com\"\r\n}"
    headers = {
        'iPlanetDirectoryPro': "token",
        'Content-Type': "application/json",
        'Cache-Control': "no-cache",
        }

    response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

    print(response.text)

1 个答案:

答案 0 :(得分:2)

这是因为您传递了 字符串 '令牌'当您的意思是传递 变量 标记

在这里创建令牌:

tokencreate = json.loads(response.text)
token=tokencreate['tokenId']
print token

但是你没有使用实际的变量,它应该是这样的:

payload = "{\r\n\"username\":\"Patrick\",\r\n\"userpassword\":\"{{userpassword}}\",\r\n\"mail\":\"patrick@example.com\"\r\n}"
headers = {
    'iPlanetDirectoryPro': token,
    'Content-Type': "application/json",
    'Cache-Control': "no-cache",
    }
相关问题