AndyM
AndyM

Reputation: 622

python how do i put a variable in command string

I'm new to python and cannot figure out how to do the following. I want to put a variable inside a command but its not working. The command is taking the variable name not its value.

The script below calls https with username and password to get a token. I token is returned . I then need to use the token to create a user. I'm having issues with it, "token" in the iplanet pair is not getting expanded correctly. It is set correctly as I can print it out before the command. So token would contain something like "AQIC5wM2LY4Sfcydd5smOKSGJT" , but when the 2nd http call is made it gets passed the word token , rather than tokens value.

    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\":\"[email protected]\"\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)

Upvotes: 0

Views: 1421

Answers (1)

Richard Stoeffel
Richard Stoeffel

Reputation: 695

It's because you are passing the string 'token' when you mean to pass the variable token

here you create the token:

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

But you don't use the actual variable, it should look like this:

payload = "{\r\n\"username\":\"Patrick\",\r\n\"userpassword\":\"{{userpassword}}\",\r\n\"mail\":\"[email protected]\"\r\n}"
headers = {
    'iPlanetDirectoryPro': token,
    'Content-Type': "application/json",
    'Cache-Control': "no-cache",
    }

Upvotes: 2

Related Questions