#!/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
本身。
有谁能告诉我我在这里做错了什么?
提前致谢。
答案 0 :(得分:1)
您可以使用字符串格式。
在您的JSON字符串中,将random_uuid替换为%s,而不是:
payload = payload % random_uuid
另一种选择是使用json.dumps
来创建json:
payload_dict = {
'id': random_uuid,
...
}
payload = json.dumps(payload_dict)
答案 1 :(得分:1)
改为使用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)
答案 2 :(得分:1)
您可以将JSON直接输入到dict
中:
payload = {
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": random_uuid,
"username": "testuser3",
"password": "bar",
"description": "biz",
"$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
}
}
答案 3 :(得分: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)