개발하자

FastAPI를 이용하여 엑셀 파일을 반납하고 다운로드하는 방법은?

Cuire 2023. 9. 13. 06:25
반응형

FastAPI를 이용하여 엑셀 파일을 반납하고 다운로드하는 방법은?

FastAPI를 사용하여 엑셀파일(버전: Office365)을 반납하는 방법은? 그 문서는 꽤 간단해 보인다. 그런데, 뭘 써야 할지 모르겠어요. 내 암호는 여기 있다:

import os
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
from typing import Optional

excel_file_path = r"C:\Users\some_path\the_excel_file.xlsx"

app = FastAPI()

class ExcelRequestInfo(BaseModel):
    client_id: str


@app.post("/post_for_excel_file/")
async def serve_excel(item: ExcelRequestInfo):
    # (Generate excel using item.)
    # For now, return a fixed excel.
    return FileResponse(
        path=excel_file_path,

        # Swagger UI says 'cannot render, look at console', but console shows nothing.
        media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

        # Swagger renders funny chars with this argument:
        # 'application/vnd.ms-excel'
    )

제가 맞았다고 가정하면 파일을 어떻게 다운받나요? Fast에서 생성한 Swagger UI를 사용할 수 있나요시트를 볼 API? 아니면 컬? 이상적으로 엑셀로 파일을 다운받아 볼 수 있으면 좋겠습니다.

해결책

클릭하지 않도록 최종(편집) 솔루션을 소개합니다. 개발 과정에서 a에서 해당 리턴으로 전환해야 했습니다.

import io
import os.path
from fastapi.responses import Response


@router.get("/customer/{customer}/sheet")
async def generate_excel(customer: str):
    excel_file_path: str = None
    buffer: io.BytesIO = None

    # Generate the sheet.
    excel_file_path, buffer = make_excel(customer=customer)

    # Return excel back to client.
    headers = {
        # By adding this, browsers can download this file.
        'Content-Disposition': f'attachment; filename={os.path.basename(excel_file_path)}',
        # Needed by our client readers, for CORS (cross origin resource sharing).
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "*",
        "Access-Control_Allow-Methods": "POST, GET, OPTIONS",
    }
    media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

    return Response(
        content=buffer.getvalue(),
        headers=headers,
        media_type=media_type
    )



답변 및 에서 설명한 대로 브라우저에 파일을 다운로드해야 함을 나타내는 를 설정할 수 있습니다. Swagger UI는 요청을 실행하는 즉시 파일을 다운로드할 수 있는 링크를 제공합니다.

headers = {'Content-Disposition': 'attachment; filename="Book.xlsx"'}
return FileResponse(excel_file_path, headers=headers)

파일을 브라우저에서 볼 수 있게 하려면 앞서 링크된 답변에서 설명한 것처럼 헤더에 매개 변수 대신 매개 변수를 사용할 수 있습니다. 그러나 브라우저가 엑셀 파일을 표시할 수 있으려면 (Excel 파일의 경우 참조) 에서 를 올바르게 설정해야 할 뿐만 아니라 (또는 ) 브라우저에 대한 알려진 파일 확장자여야 한다(이는 일반적으로 브라우저 확장자/플러그인을 통해 달성된다.


반응형