python-requests与CURL的相互转换

主要记录一下requests模块发送的请求与CURL命令发送请求之间的相互转换。

requests代码转为CURL命令

  1. 安装 curlfy 第三方库
pip3 install curlify -i https://pypi.douban.com/simple
  1. github地址及使用:https://github.com/ofw/curlify
  2. 实例
import curlify
import requests

rep = requests.get("https://www.baidu.com")
ret1 = curlify.to_curl(rep.request)
print(ret1)# 这种形式,需要输出成一个二进制文件,后面需要再加上 --output (文件名)
"""
curl -X GET -H 'Accept: */*' -H 'Accept-Encoding: gzip, deflate' -H 'Connection: keep-alive' -H 'User-Agent: python-requests/2.23.0' https://www.baidu.com/
"""

ret2 = curlify.to_curl(rep.request,compressed=True)
print(ret2)
"""
curl -X GET -H 'Accept: */*' -H 'Accept-Encoding: gzip, deflate' -H 'Connection: keep-alive' -H 'User-Agent: python-requests/2.23.0' --compressed https://www.baidu.com/
"""

CURL命令转为requests代码

github有一个curlconverter工具很好用:https://github.com/NickCarneiro/curlconverter

如下curl命令:
curl --request POST --url https://open.workec.com/auth/accesstoken --header 'cache-control: no-cache' --header 'content-type: application/json' --data '{ 'appId': appId, 'appSecret': 'appSecret'}'

由于这个工具使用node.js写的,因从我们得使用npm安装它:

$ npm install --save curlconverter

安装完毕后创建一个名为 curl_test.js的测试文件,里面的内容如下:

var curlcon = require("curlconverter"); 
ret = curlcon.toPython("curl --request POST --url https://open.workec.com/auth/accesstoken --header 'cache-control: no-cache' --header 'content-type: application/json' --data '{ 'appId': appId, 'appSecret': 'appSecret'}'") console.log(ret)

然后在终端执行 node curl_test.js

可以看到:终端打印出了转换后的结果。

import requests

headers = {
    'cache-control': 'no-cache',
    'content-type': 'application/json',
}

data = '{ "appId": appId, "appSecret": "appSecret"}'

response = requests.post('https://open.workec.com/auth/accesstoken', headers=headers, data=data)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值