59

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)    
4

2 回答 2

79

您也可以使用curlify来执行此操作。

$ pip install curlify
...
import curlify
print(curlify.to_curl(r.request))  # r is the response object from the requests library.
于 2018-06-20T07:46:38.470 回答
62

这种方法曾经存在于请求中,但它与模块远不相关。您可以创建一个接受响应并检查其request属性的函数。

request属性是一个PreparedRequest对象,因此它具有headersbody属性。正文是您传递给 curl 的内容,-d并且可以像上面那样生成标题。最后,您需要urlrequest对象中提取属性并将其发送。除非您使用自定义身份验证处理程序做某事,否则这些钩子对您来说并不重要。

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)

应该行得通。您的数据将被正确格式化,无论是 asmultipart/form-data还是其他。

于 2013-07-30T00:51:28.047 回答