Build Flask WAF log converter app
This commit is contained in:
43
app/services/storage.py
Normal file
43
app/services/storage.py
Normal file
@@ -0,0 +1,43 @@
|
||||
import json
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from app.services.exporter import ExportResult
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ResultMetadata:
|
||||
result_id: str
|
||||
file_path: str
|
||||
download_name: str
|
||||
mimetype: str
|
||||
|
||||
|
||||
def persist_result(output_dir: Path, export_result: ExportResult) -> ResultMetadata:
|
||||
"""Persist generated output and sidecar metadata in a temporary directory."""
|
||||
result_id = uuid.uuid4().hex
|
||||
extension = "txt" if export_result.output_format == "text" else "csv"
|
||||
mimetype = "text/plain; charset=utf-8" if extension == "txt" else "text/csv; charset=utf-8"
|
||||
|
||||
file_path = output_dir / f"{result_id}.{extension}"
|
||||
metadata_path = output_dir / f"{result_id}.json"
|
||||
|
||||
file_path.write_text(export_result.content, encoding="utf-8")
|
||||
metadata = ResultMetadata(
|
||||
result_id=result_id,
|
||||
file_path=str(file_path),
|
||||
download_name=f"waf-report.{extension}",
|
||||
mimetype=mimetype,
|
||||
)
|
||||
metadata_path.write_text(json.dumps(asdict(metadata)), encoding="utf-8")
|
||||
return metadata
|
||||
|
||||
|
||||
def load_result_metadata(output_dir: Path, result_id: str) -> dict[str, str] | None:
|
||||
"""Load sidecar metadata for a generated file."""
|
||||
metadata_path = output_dir / f"{result_id}.json"
|
||||
if not metadata_path.exists():
|
||||
return None
|
||||
|
||||
return json.loads(metadata_path.read_text(encoding="utf-8"))
|
||||
Reference in New Issue
Block a user