[32788f42] feat(list-generator): create React app and FastAPI backend for PDF list generation
This commit is contained in:
46
list-generator/backend/app/routers/generate.py
Normal file
46
list-generator/backend/app/routers/generate.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from fastapi import APIRouter, File, UploadFile, Form, HTTPException
|
||||
from fastapi.responses import FileResponse
|
||||
from typing import Optional
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from ..services.pdf_generator import generate_school_pdf
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/generate-list")
|
||||
async def generate_list(
|
||||
institution: str = Form(...),
|
||||
date_info: str = Form(...),
|
||||
list_type: str = Form("k"),
|
||||
students_file: UploadFile = File(...),
|
||||
families_file: Optional[UploadFile] = File(None)
|
||||
):
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
students_path = os.path.join(temp_dir, "students.csv")
|
||||
with open(students_path, "wb") as buffer:
|
||||
shutil.copyfileobj(students_file.file, buffer)
|
||||
families_path = None
|
||||
if families_file:
|
||||
families_path = os.path.join(temp_dir, "families.csv")
|
||||
with open(families_path, "wb") as buffer:
|
||||
shutil.copyfileobj(families_file.file, buffer)
|
||||
pdf_path = generate_school_pdf(
|
||||
institution=institution,
|
||||
date_info=date_info,
|
||||
list_type=list_type,
|
||||
students_csv_path=students_path,
|
||||
families_csv_path=families_path,
|
||||
output_dir=temp_dir
|
||||
)
|
||||
if not pdf_path or not os.path.exists(pdf_path):
|
||||
raise HTTPException(status_code=500, detail="PDF generation failed")
|
||||
with open(pdf_path, "rb") as f:
|
||||
pdf_bytes = f.read()
|
||||
final_output_path = os.path.join("/tmp", os.path.basename(pdf_path))
|
||||
with open(final_output_path, "wb") as f:
|
||||
f.write(pdf_bytes)
|
||||
return FileResponse(path=final_output_path, filename=os.path.basename(pdf_path), media_type="application/pdf")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
Reference in New Issue
Block a user