2016-04-13 91 views
0
#!/usr/bin/python 
import requests 
import uuid 

random_uuid = uuid.uuid4() 
print random_uuid 
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials" 

payload = '''json={ 
     "": "0", 
     "credentials": { 
      "scope": "GLOBAL", 
      "id": "random_uuid", 
      "username": "testuser3", 
      "password": "bar", 
      "description": "biz", 
      "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl" 
     } 
    }''' 
headers = { 
    'content-type': "application/x-www-form-urlencoded", 
    } 

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

print(response.text) 

在上面的脚本中,我创建了一个UUID并将其分配给变量random_uuid。我想要创建的UUID被替换为json内部的值为random_uuid的密钥id。但是,上面的脚本并不代替random_uuid的值,而只是使用变量random_uuid本身。如何在python中将变量替换为json中的变量?

任何人都可以告诉我我在做什么错在这里?

在此先感谢。

回答

0

你可以使用字符串格式。

在你的JSON字符串替换random_uuid与%s,比办:

payload = payload % random_uuid 

另一种选择是使用json.dumps创建JSON:

payload_dict = { 
    'id': random_uuid, 
    ... 
} 

payload = json.dumps(payload_dict) 
+0

非常感谢。有效。 –

0

此代码可能会有帮助。

#!/usr/bin/python 
import requests 
import uuid 

random_uuid = uuid.uuid4() 
print random_uuid 
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials" 

payload = '''json={ 
     "": "0", 
     "credentials": { 
      "scope": "GLOBAL", 
      "id": "%s", 
      "username": "testuser3", 
      "password": "bar", 
      "description": "biz", 
      "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl" 
     } 
    }''' % random_uuid 
headers = { 
    'content-type': "application/x-www-form-urlencoded", 
    } 

print payload 

print(response.text) 
0

使用str.format代替:

payload = '''json={ 
     "": "0", 
     "credentials": { 
      "scope": "GLOBAL", 
      "id": "{0}", 
      "username": "testuser3", 
      "password": "bar", 
      "description": "biz", 
      "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl" 
     } 
    }'''.format(random_uuid)