Initial commit: Add curl-to-code-cli project
This commit is contained in:
58
.curl_to_code/generators/python_gen.py
Normal file
58
.curl_to_code/generators/python_gen.py
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
from ..parser.models import ParsedCurl
|
||||||
|
|
||||||
|
|
||||||
|
def generate_python(parsed: ParsedCurl) -> str:
|
||||||
|
"""Generate Python requests code from parsed curl command."""
|
||||||
|
lines = [
|
||||||
|
"import requests",
|
||||||
|
"from requests.auth import HTTPBasicAuth",
|
||||||
|
"import json",
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
"def make_request():",
|
||||||
|
f' url = "{parsed.url}"',
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
|
||||||
|
if parsed.auth and parsed.auth.username and parsed.auth.password:
|
||||||
|
lines.append(f' auth = HTTPBasicAuth("{parsed.auth.username}", "{parsed.auth.password}")')
|
||||||
|
else:
|
||||||
|
lines.append(" auth = None")
|
||||||
|
|
||||||
|
headers_dict = {h.key: h.value for h in parsed.headers}
|
||||||
|
if parsed.user_agent:
|
||||||
|
headers_dict["User-Agent"] = parsed.user_agent
|
||||||
|
|
||||||
|
lines.append(f" headers = {headers_dict}")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
method_name = parsed.method.value.lower()
|
||||||
|
if parsed.data:
|
||||||
|
if parsed.data.data_type.value == "json":
|
||||||
|
lines.append(f" json_data = {parsed.data.json_data}")
|
||||||
|
lines.append(f" response = requests.{method_name}(url, json=json_data, headers=headers, auth=auth)")
|
||||||
|
else:
|
||||||
|
lines.append(f" data = {repr(parsed.data.content)}")
|
||||||
|
lines.append(f" response = requests.{method_name}(url, data=data, headers=headers, auth=auth)")
|
||||||
|
else:
|
||||||
|
lines.append(f" response = requests.{method_name}(url, headers=headers, auth=auth)")
|
||||||
|
|
||||||
|
if parsed.timeout:
|
||||||
|
lines[-1] = lines[-1][:-1] + f", timeout={parsed.timeout})")
|
||||||
|
|
||||||
|
lines.extend([
|
||||||
|
"",
|
||||||
|
" try:",
|
||||||
|
" response.raise_for_status()",
|
||||||
|
" print(response.json())",
|
||||||
|
" except requests.exceptions.RequestException as e:",
|
||||||
|
' print(f"Error: {e}")',
|
||||||
|
" except ValueError as e:",
|
||||||
|
' print(f"JSON decode error: {e}")',
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
"if __name__ == \"__main__\":",
|
||||||
|
" make_request()",
|
||||||
|
])
|
||||||
|
|
||||||
|
return "\n".join(lines)
|
||||||
Reference in New Issue
Block a user