wip: add import endpoint

This commit is contained in:
Jakub Miazek
2024-02-17 08:40:49 +01:00
parent cd3ce997d8
commit 101fa05515
3 changed files with 42 additions and 6 deletions

View File

@@ -1,4 +1,7 @@
from fastapi import APIRouter, Depends, status
import io
from fastapi import APIRouter, Depends, status, UploadFile, HTTPException
from sqlalchemy.exc import SQLAlchemyError
import polars as pl
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
@@ -48,3 +51,37 @@ async def merge_nonsense(
nonsense = Nonsense(**payload.model_dump())
await nonsense.save_or_update(db_session)
return nonsense
@router.post(
"/import",
status_code=status.HTTP_201_CREATED,
)
async def import_nonsense(
xlsx: UploadFile,
db_session: AsyncSession = Depends(get_db),
):
file_bytes = await xlsx.read()
nonsense_data = pl.read_excel(
source=io.BytesIO(file_bytes),
sheet_name="New Nonsense",
engine="calamine",
)
try:
nonsense_records = [
Nonsense(
name=nonsense.get("name"),
description=nonsense.get("description"),
)
for nonsense in nonsense_data.to_dicts()
]
db_session.add_all(nonsense_records)
await db_session.commit()
return {"filename": xlsx.filename, "nonsense_records": len(nonsense_records)}
except (SQLAlchemyError, HTTPException) as ex:
await db_session.rollback()
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)) from ex
finally:
await db_session.close()