求助:将Curl GET请求转为Python 2.7.5 Requests代码及字典转内联JSON
Hey there! Let's get that curl command converted to Python 2.7.5's requests module sorted out. Since you didn't share the exact curl command you're running, I'll walk you through a general conversion workflow with a realistic example, plus cover the most common gotchas that trip people up when making this switch.
First, let's map curl's flags to their requests equivalents—this makes conversion straightforward:
- The core URL: Goes directly as the first argument to
requests.get() - Headers (
-H "Key: Value"): Pack these into a Python dictionary and pass via theheadersparameter - Query parameters (either in the URL, or
-d "param=val"for GET): Use theparamsdictionary to letrequestshandle encoding correctly - Basic auth (
-u user:pass): Pass a tupleauth=("username", "password") - Cookies (
-b "cookie=val"): Use thecookiesdictionary parameter
Let's say your working curl command looks like this:
curl -X GET "https://api.your-service.com/endpoint" \ -H "Authorization: Token YOUR_API_KEY" \ -H "Accept: application/json" \ -d "filter=active&per_page=20"
Here's how to translate that to Python 2.7.5-compatible code:
First, make sure you have the right version of requests installed (Python 2.7 only supports up to requests 2.27.1):
pip install requests==2.27.1
Then the Python code:
import requests # Base API URL url = "https://api.your-service.com/endpoint" # Match the headers from your curl command headers = { "Authorization": "Token YOUR_API_KEY", "Accept": "application/json" } # Query parameters from the `-d` flag (GET requests use these in the URL) params = { "filter": "active", "per_page": 20 } try: # Send the GET request response = requests.get(url, headers=headers, params=params) # Raise an error if the request failed (4xx/5xx status codes) response.raise_for_status() # Parse the JSON response (adjust if the API returns plain text/XML) response_data = response.json() print("Request succeeded! Data:", response_data) except requests.exceptions.RequestException as e: # Catch all request-related errors (network issues, bad status codes, etc.) print("Request failed with error:", e) # Optional: Print the raw response content for debugging print("Raw response content:", response.content)
- Python 2.7 String Encoding: If you're dealing with non-ASCII characters, use Unicode strings (
u"your-string") to avoid encoding errors - SSL Verification: If your curl uses
-kto skip SSL checks, addverify=Falsetorequests.get()(note: this is insecure for production use!) - Body vs. Query Params: For GET requests, curl's
-dadds query parameters, not request body data. Don't mix these up with thedataparameter inrequests(that's for POST bodies) - Cookie Handling: If your curl uses
-bto send cookies, map them to acookiesdictionary likecookies={"session_id": "your-id"}
If you share your exact curl command, I can tweak this example to match your use case perfectly!
内容的提问来源于stack exchange,提问作者NigelM

