将CURL转换为Python rest apt调用

2024-04-29 08:51:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Jenkins中通过api调用发布,下面的CURL命令可以正常工作,参数应用正确

curl -X POST -v http://localhost:8080/job/DNS_Tool_v1/build --user user01:1231121212121212121212 --data-urlencode json='{"parameter": [{"name": "registration_action","value": "DDNS_only"},{"name": "Note:", "value": "test01"},{"name": "entries","value": "add, hostname01.local.example.com, 192.168.1.1/24\nremove, hostname01.local.example.com, 192.168.1.1/24\n" }]}'

但是由于某些原因,请求POST没有从dict中转储值。这段代码有什么问题?有什么想法吗?多谢各位

PYTHON代码:

params = {'parameter': [{"name": "registration_action", "value": "DDNS_only"}, \
          {"name": "Note:", "value": "test01"}, \
          {"name": "entries","value": "add, hostname01.local.example.com, 192.168.1.1/24\nremove, hostname01.local.example.com, 192.168.1.1/24\n" }]}

data = {'json': json.dumps(params)}
job_url = "http://{0}:{1}@{2}/job/{3}/{4}".format(user, pswd, jenkins_host, jenkins_job, jenking_action)
# output of job_url >> http://user01:1231121212121212121212@localhost:8080/job/DNS_Tool_v1/build
response = requests.post(job_url,headers={'content-type': 'application/json'},data=data)

我得到的输出响应:<Response [201]>但是当我看到创建的作业时,没有传入任何参数

更新代码,仍然错误:

url = "http://localhost:8080"    
auth = (user, pswd)
crumb_data = requests.get("{0}/crumbIssuer/api/json".format(url),auth = auth,headers={'content-type': 'application/json'}, verify=False)
print(crumb_data.content)
print(crumb_data.json()['crumb'])
job_url = "http://{0}:{1}@localhost:8080/buildWithParameters".format(user, pswd)
headers = {'content-type': 'application/json', 'Jenkins-Crumb':crumb_data.json()['crumb']}
response = requests.post(job_url,headers=headers, json=params, verify=False)
print(response.text.encode('UTF-8'))

错误

b'<html>\n<head>\n<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>\n<title>Error 403 No valid crumb was included in the request</title>\n</head>\n<body><h2>HTTP ERROR 403</h2>\n<p>Problem accessing /job/coreinfra/job/prod/job/DNStool/job/DDNS_Tool_v1/buildWithParameters. Reason:\n<pre>    No valid crumb was included in the request</pre></p><hr><a href="http://eclipse.org/jetty">Powered by Jetty:// 9.4.z-SNAPSHOT</a><hr/>\n\n</body>\n</html>\n'

Tags: namejsonlocalhosthttpurldatavalueexample