Files

51 lines
2.1 KiB
Python

from fastapi import APIRouter, File, UploadFile, Form, HTTPException
from fastapi.responses import FileResponse
from typing import Optional
import os
import shutil
import tempfile
import traceback
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)
print(f"Generating PDF for: {institution}, Type: {list_type}")
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 - file not created.")
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:
print("ERROR IN GENERATE LIST:")
traceback.print_exc()
raise HTTPException(status_code=500, detail=f"Internal Server Error: {str(e)}")