71 lines
1.8 KiB
Python
71 lines
1.8 KiB
Python
"""cURL exporter for HTTP entries."""
|
|
|
|
|
|
from http_log_explorer.models import HTTPEntry
|
|
|
|
|
|
class CurlExporter:
|
|
"""Export HTTP entries as cURL commands."""
|
|
|
|
def export(self, entry: HTTPEntry) -> str:
|
|
"""Export a single entry as cURL command.
|
|
|
|
Args:
|
|
entry: HTTPEntry object
|
|
|
|
Returns:
|
|
cURL command string
|
|
"""
|
|
parts = ["curl"]
|
|
|
|
parts.append("-X")
|
|
parts.append(entry.request.method)
|
|
|
|
if entry.request.headers:
|
|
for name, value in entry.request.headers.items():
|
|
if name.lower() not in ("host", "content-length"):
|
|
parts.append("-H")
|
|
parts.append(f"{name}: {value}")
|
|
|
|
if entry.request.body:
|
|
escaped_body = self._escape_body(entry.request.body)
|
|
parts.append("-d")
|
|
parts.append(f"'{escaped_body}'")
|
|
|
|
parts.append(f"'{entry.request.url}'")
|
|
|
|
return " ".join(parts)
|
|
|
|
def export_batch(self, entries: list[HTTPEntry]) -> list[str]:
|
|
"""Export multiple entries as cURL commands.
|
|
|
|
Args:
|
|
entries: List of HTTPEntry objects
|
|
|
|
Returns:
|
|
List of cURL command strings
|
|
"""
|
|
return [self.export(entry) for entry in entries]
|
|
|
|
def _escape_body(self, body: str) -> str:
|
|
"""Escape body string for shell.
|
|
|
|
Args:
|
|
body: Body content
|
|
|
|
Returns:
|
|
Escaped string
|
|
"""
|
|
return body.replace("'", "'\\''")
|
|
|
|
def to_file(self, entries: list[HTTPEntry], path: str) -> None:
|
|
"""Write cURL commands to file (one per line).
|
|
|
|
Args:
|
|
entries: List of HTTPEntry objects
|
|
path: Output file path
|
|
"""
|
|
with open(path, "w") as f:
|
|
for entry in entries:
|
|
f.write(self.export(entry) + "\n")
|