作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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)
最佳答案
您也可以使用curlify去做这个。
$ pip install curlify
...
import curlify
print(curlify.to_curl(r.request)) # r is the response object from the requests library.
关于python-requests - 如何从 python requests 模块构造 curl 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17936555/
我是一名优秀的程序员,十分优秀!