requests與CURL的相互轉換


主要記錄一下requests模塊發送的請求與CURL命令發送請求之間的相互轉換。

requests代碼轉為CURL命令

安裝curlify模塊:

pip3 install curlify -i https://pypi.douban.com/simple

github地址及使用

https://github.com/ofw/curlify

實例

import curlify
import requests

rep = requests.get("https://www.baidu.com")
ret1 = curlify.to_curl(rep.request)
print(ret1)
"""
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/
"""

源碼及參數說明

源碼中to_curl有2個參數:compressed(默認為False),verify(默認為True):

 

CURL命令轉為requests代碼

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

實例1 使用node環境

如下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

可以看到:終端打印出了轉換后的結果。

實例2 使用項目提供的在線工具

還是實例1的curl命令,我們使用在線工具轉換為requests代碼效果如下:

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)

curl命令的常用參數參考

curl命令常用參數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM