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's debug中的好示例,我找不到一种简单的构造方法,下面是我要创建的方法我自己。
# 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)
答案 0 :(得分:28)
这种方法曾经存在于请求中,但远不是与模块远程相关。您可以创建一个接收响应并检查其request
属性的函数。
request
属性是PreparedRequest
对象,因此它具有headers
和body
属性。身体是你传递给-d
卷曲的身体,你可以像上面那样生成标题。最后,您需要从url
对象中取出request
属性并发送它。除非您使用自定义身份验证处理程序执行某些操作,否则挂钩对您无关紧要。
req = response.request
command = "curl -X {method} -H {headers} -d '{data}' '{uri}'"
method = req.method
uri = req.url
data = req.body
headers = ['"{0}: {1}"'.format(k, v) for k, v in req.headers.items()]
headers = " -H ".join(headers)
return command.format(method=method, headers=headers, data=data, uri=uri)
应该工作。无论是multipart/form-data
还是其他任何内容,您的数据都将被正确格式化。
答案 1 :(得分:13)
您也可以使用curlify进行此操作。
$ pip install curlify
...
import curlify
print(curlify.to_curl(r.request)) // r is the response object from the requests lib