將 curl 命令轉換為 Python 程式碼 - 為 API 請求生成即用型 Python requests 程式碼
# Python requests code will appear here # Example: import requests url = "https://api.example.com/data" payload = {"name": "test"} headers = { "Content-Type": "application/json" } response = requests.post(url, json=payload, headers=headers) print(response.status_code) print(response.text)
以下是一些可以轉換為 Python 程式碼的常見 curl 命令:
curl https://api.example.com/users
curl -X POST -H "Content-Type: application/json" -d '{"name":"John","email":"[email protected]"}' https://api.example.com/users
curl -X PUT -H "Authorization: Bearer token123" -d '{"status":"active"}' https://api.example.com/users/1
curl -X DELETE https://api.example.com/users/1
curl -H "X-API-Key: abc123" -H "Accept: application/json" https://api.example.com/data
Python 的 requests 庫是一種強大且優雅的方式來發出 HTTP 請求。以下是一些常見的 Python requests 模式:
import requests url = "https://api.example.com/upload" files = {'file': open('document.pdf', 'rb')} headers = {"Authorization": "Bearer YOUR_TOKEN_HERE"} response = requests.post(url, files=files, headers=headers) print(response.json())
import requests from requests.exceptions import RequestException url = "https://api.example.com/data" try: response = requests.get(url, timeout=5) response.raise_for_status() # Raises exception for 4XX/5XX responses data = response.json() print(data) except RequestException as e: print(f"Error making request: {e}")
複製您的 curl 命令 → 貼到輸入框 → 獲取轉換後的 Python requests 程式碼
我們的進階轉換器支援複雜的 curl 命令,並將其轉換為乾淨、高效且可用於生產環境的 Python 程式碼,使用 requests 庫。完美適用於 API 開發、測試和整合。
我們的工具處理這些常見的 curl 選項並將它們轉換為適當的 Python requests 程式碼:
答:生成的 Python requests 程式碼完全相容於 Python 3.x(3.6 及以上版本)。對於 Python 2.x,可能需要進行小幅調整,不過我們建議使用 Python 3 以獲得更好的安全性和功能支援。
答:基本生成的程式碼不包含廣泛的錯誤處理。對於生產環境的程式碼,您應該添加 try/except 區塊來處理潛在的異常,如 requests.exceptions.RequestException。
答:requests 庫使處理回應變得容易。使用 response.json() 處理 JSON 回應,response.text 處理文字內容,或 response.content 處理二進制資料。
答:是的,如果您尚未安裝 requests 庫,則需要安裝它。您可以使用 pip 進行安裝:pip install requests
答:對於 Python 中的檔案上傳,您需要在 requests.post() 方法中使用 files 參數。我們的轉換器處理帶有 -F
或 --form
選項的 curl 命令,並使用 requests 庫生成適當的 Python 程式碼。
答:Python 的 requests 庫通過 Session 物件使 cookie 處理變得簡單。當您轉換包含 cookie 處理的 curl 命令(使用 -b
或 --cookie
)時,我們的工具會生成使用 requests.Session() 正確管理 cookie 的 Python 程式碼。
答:雖然 curl 非常適合快速命令行 API 測試,但 Python requests 提供了一種程式化方法,可與您的 Python 應用程式整合。將 curl 轉換為 Python 有助於縮小 Python 開發中測試和實現之間的差距。
了解 curl 命令對於使用 Python 進行有效的 API 測試至關重要。以下是我們的轉換器支援的常見 curl 選項的快速參考:
curl [options] [URL]
-X, --request METHOD
: Specify request method (GET, POST, PUT, DELETE, etc.)-H, --header LINE
: Add header to the request-d, --data DATA
: Send data in POST request-F, --form CONTENT
: Submit form data-u, --user USER:PASSWORD
: Server user and password-k, --insecure
: Allow insecure server connections-I, --head
: Show document info only-v, --verbose
: Make the operation more verbose-s, --silent
: Silent mode--connect-timeout SECONDS
: Maximum time for connection我們的 Python 轉換器處理複雜的 curl 命令,包括多個標頭、身份驗證、資料負載和各種選項。只需貼上您的 curl 命令,即可獲得使用 requests 庫的乾淨、現代的 Python 程式碼。
使用 Python requests 庫時,請遵循這些最佳實踐,以實現高效且安全的 API 互動:
import requests session = requests.Session() session.headers.update({"Authorization": "Bearer token123"}) # First request response1 = session.get("https://api.example.com/users") # Second request (uses same session) response2 = session.get("https://api.example.com/products") # Close the session when done session.close()
import requests from requests.exceptions import HTTPError, ConnectionError, Timeout try: response = requests.get("https://api.example.com/data", timeout=5) response.raise_for_status() except HTTPError as e: print(f"HTTP error occurred: {e}") except ConnectionError as e: print(f"Connection error occurred: {e}") except Timeout as e: print(f"Timeout error occurred: {e}") except Exception as e: print(f"An error occurred: {e}")
import requests import json response = requests.get("https://api.example.com/data") try: data = response.json() except json.JSONDecodeError: print("Response was not valid JSON") data = {}