gpt4 book ai didi

python-requests - 如何从 python requests 模块构造 curl 命令?

转载 作者:行者123 更新时间:2023-12-03 10:20:47 30 4
gpt4 key购买 nike

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com