首頁  >  文章  >  後端開發  >  python中CURL和python requests的相互轉換如何實現

python中CURL和python requests的相互轉換如何實現

WBOY
WBOY轉載
2023-05-03 12:49:131266瀏覽

curl 和 Python requests 都是發送 HTTP 請求的強大工具。雖然 curl 是一種命令列工具,可讓您直接從終端機發送請求,但 Python 的請求庫提供了一種更具程式化的方式來從 Python 程式碼中發送請求。

將curl 轉換為Python requests

curl 指令的基本語法如下所示:

curl [OPTIONS] URL

將curl 指令轉換為Python 請求時,我們需要將選項和URL 轉換為Python 程式碼。

這是一個範例curl POST 指令:

curl -X POST https://example.com/api/v1/users \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer YOUR_API_KEY' \
    -d '{"username": "john_doe", "email": "john_doe@example.com"}'

要將此curl 指令轉換為Python 請求,我們可以編寫以下程式碼:

import requests

url = 'https://example.com/api/v1/users'
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
}
data = {
    'username': 'john_doe',
    'email': 'john_doe@example.com'
}

response = requests.post(url, headers=headers, json=data)

print(response.status_code)
print(response.json())

在此範例中,我們使用requests.post() 方法向URL https://example.com/api/v1/users 發送POST 請求,JSON 有效負載為{“username”: “john_doe”, “電子郵件”:“john_doe@example.com ”}`。我們還包括 Content-Type 和 Authorization 標頭。

將 Python 請求轉換為 curl

將 Python 請求程式碼轉換為 curl 命令有點棘手,因為在命令列上沒有直接等效的請求庫。但是,我們可以使用 --data 或 -d 選項將資料傳遞給 curl 命令,並使用 -H 選項設定標頭。

這是一個範例Python GET 請求腳本:

import requests

url = 'https://example.com/api/v1/users'
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
}
params = {
    'username': 'john_doe',
    'sort': 'name',
    'order': 'asc'
}

response = requests.get(url, headers=headers, params=params)

print(response.status_code)
print(response.json())

要將此Python 請求程式碼轉換為curl 指令,我們可以使用下列指令:

curl -X GET 'https://example.com/api/v1/users?username=john_doe&sort=name&order=asc' \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer YOUR_API_KEY'

在此範例中,我們使用-X GET 選項指定我們發送GET 請求,並將URL 和查詢參數作為字串傳遞。我們還包括 Content-Type 和 Authorization 標頭。

以上是python中CURL和python requests的相互轉換如何實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除