|
| 1 | +from typing import Any |
| 2 | + |
| 3 | +from fastapi import APIRouter, BackgroundTasks, File, HTTPException, UploadFile |
| 4 | + |
| 5 | +from app.api.deps import CurrentUser, SessionDep |
| 6 | +from app.models import Document, DocumentCreate, DocumentPublic |
| 7 | +from app.s3 import generate_s3_url, upload_file_to_s3 |
| 8 | + |
| 9 | +router = APIRouter(prefix="/documents", tags=["documents"]) |
| 10 | + |
| 11 | + |
| 12 | +@router.post("/", response_model=DocumentPublic) |
| 13 | +def create_document( |
| 14 | + *, |
| 15 | + session: SessionDep, |
| 16 | + current_user: CurrentUser, |
| 17 | + background_tasks: BackgroundTasks, # noqa: ARG001 |
| 18 | + file: UploadFile = File(...), |
| 19 | +) -> Any: |
| 20 | + key = None |
| 21 | + try: |
| 22 | + key = upload_file_to_s3(file, str(current_user.id)) |
| 23 | + except Exception as e: |
| 24 | + raise HTTPException(500, f"Failed to upload file. Error: {str(e)}") |
| 25 | + |
| 26 | + try: |
| 27 | + url = generate_s3_url(key) |
| 28 | + except Exception: |
| 29 | + raise HTTPException(500, f"Could not generate URL for file key: {key}") |
| 30 | + |
| 31 | + document_in = DocumentCreate( |
| 32 | + filename=file.filename, |
| 33 | + content_type=file.content_type, |
| 34 | + size=file.size, |
| 35 | + s3_url=url, |
| 36 | + ) |
| 37 | + |
| 38 | + document = Document.model_validate( |
| 39 | + document_in, update={"owner_id": current_user.id} |
| 40 | + ) |
| 41 | + |
| 42 | + session.add(document) |
| 43 | + session.commit() |
| 44 | + session.refresh(document) |
| 45 | + |
| 46 | + # 3. Kick off background job |
| 47 | + print("Document created, starting background task...") |
| 48 | + # background_tasks.add_task(generate_questions, document.id) |
| 49 | + |
| 50 | + return document |
0 commit comments