Python requests是一个很好的模块来简化我的 web REST API 访问编程,我通常如下所示
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
当出现错误时,我想看看它背后发生了什么。在命令行中构造curl
命令来重现是常用的方式,因为这是在 RESP API 文档中描述最多的标准方式
try:
r = requests.post(url, data=json.dumps(payload), headers=headers)
except Exception as ex:
print "try to use curl command below to reproduce"
print curl_request(url,"POST",headers,payload)
很高兴我可以curl
为这个请求生成命令示例,在libcloud 的调试中查看很好的示例,我找不到简单的构造方法,下面是我想自己创建的方法。
# below code is just pseudo code, not correct
def curl_request(url,method,headers,payloads):
# construct curl sample from requests' structure
# $ curl -v -H "Accept: application/json" -H "Content-type: application/json"
# -d '{"some":"data"}'
# -X POST https://api.github.com/some/endpoint
request = "curl -v "
for header in headers:
print header
request = request + '-H "' + header + ": " + headers[header] + '" '
for payload in payloads:
request = request + '-d {} "' + payload + ": " + payloads[payload] + '" '
request = request + "-X %s %s" % (method,url)
return request
如果我们已经有方法也requests
很好
以下是获得答案的最终解决方案,对我有用。在此处显示以供您参考
def curl_request(url,method,headers,payloads):
# construct the curl command from request
command = "curl -v -H {headers} {data} -X {method} {uri}"
data = ""
if payloads:
payload_list = ['"{0}":"{1}"'.format(k,v) for k,v in payloads.items()]
data = " -d '{" + ", ".join(payload_list) + "}'"
header_list = ['"{0}: {1}"'.format(k, v) for k, v in headers.items()]
header = " -H ".join(header_list)
print command.format(method=method, headers=header, data=data, uri=url)