mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2025-11-30 13:20:40 +03:00
wip: add import endpoint
This commit is contained in:
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user