FastAPI tips
Excel 다운로드 API
by 스티브 십잡스
2024. 5. 8.
from fastapi import FastAPI, Request, HTTPException
app = FastAPI()
'''
엑셀 파일 생성
'''
from fastapi.responses import StreamingResponse
import pandas as pd
import openpyxl
from datetime import datetime
from io import BytesIO
async def make_excel_file(cols: list, rows: list) -> StreamingResponse:
buffer = BytesIO()
df = pd.DataFrame(data=[rows], columns=cols)
file_name = f"example_{datetime.now().date()}"
encoded_file_name = file_name.encode('utf-8').decode('cp949')
# filename은 front에서도 지정 가능
headers = {
"Content-Disposition": f'attachment; filename="{encoded_file_name}.xlsx"',
}
with pd.ExcelWriter(buffer, engine="openpyxl") as writer:
df.to_excel(writer, index=False)
return StreamingResponse(
BytesIO(buffer.getvalue()),
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers=headers,
)
@app.post("/excel")
async def download(command: GetExampleRequest, db: Session = Depends(get_db)):
# return {"cols": [...], "rows": [...]}
resp = await example.get_data_for_excel(command=command, db=db)
return await excel.make_excel_file(cols=resp['cols'], rows=resp['rows'])