Files
curl-converter-cli/curlconverter/generators/python.py
7000pctAUTO bc3dd3c0cf
Some checks failed
CI / test (push) Has been cancelled
Fix CI issues: add workflow file and fix lint errors
2026-03-22 10:53:55 +00:00

91 lines
2.9 KiB
Python

{"""Python code generator."""
import json
import base64
from curlconverter.parser import ParsedCurl
from curlconverter.generators import register_generator
def _detect_content_type(headers: dict, data: str) -> str:
"""Detect content type from headers or data."""
if "Content-Type" in headers:
return headers["Content-Type"]
if "content-type" in headers:
return headers["content-type"]
if data:
try:
json.loads(data)
return "application/json"
except (json.JSONDecodeError, TypeError):
pass
return "application/x-www-form-urlencoded"
@register_generator("python")
def generate_python(parsed: ParsedCurl) -> str:
"""Generate Python requests code from parsed curl data."""
lines = []
lines.append("import requests")
lines.append("")
lines.append("url = " + repr(parsed.url))
lines.append("")
kwargs = []
headers = dict(parsed.headers) if parsed.headers else {}
if parsed.user_agent and "User-Agent" not in headers and "user-agent" not in headers:
headers["User-Agent"] = parsed.user_agent
if headers:
lines.append("headers = " + _format_dict(headers))
kwargs.append("headers=headers")
if parsed.auth:
if ":" in parsed.auth[0]:
try:
encoded = base64.b64encode(f"{parsed.auth[0]}:{parsed.auth[1]}".encode()).decode()
if "Authorization" not in headers:
headers["Authorization"] = f"Basic {encoded}"
except Exception:
pass
if parsed.data:
content_type = _detect_content_type(headers, parsed.data)
if content_type == "application/json":
try:
json_data = json.loads(parsed.data)
lines.append("data = " + json.dumps(json_data, indent=4))
kwargs.append("json=data")
except (json.JSONDecodeError, TypeError):
lines.append("data = " + repr(parsed.data))
kwargs.append("data=data")
else:
lines.append("data = " + repr(parsed.data))
kwargs.append("data=data")
if parsed.cookies:
lines.append("cookies = " + repr(parsed.cookies))
kwargs.append("cookies=cookies")
if kwargs:
kwargs_str = ",\n ".join(kwargs)
lines.append(f"response = requests.{parsed.method.lower()}(url, {kwargs_str})")
else:
lines.append(f"response = requests.{parsed.method.lower()}(url)")
lines.append("")
lines.append("print(response.status_code)")
lines.append("print(response.text)")
return "\n".join(lines)
def _format_dict(d: dict) -> str:
"""Format a dictionary for Python code."""
if not d:
return "{}"
items = []
for k, v in d.items():
items.append(f" {repr(k)}: {repr(v)}")
return "{\n" + ",\n".join(items) + "\n}"