Как вернуть и загрузить файл Excel с помощью FastAPI?Python

Программы на Python
Ответить
Anonymous
 Как вернуть и загрузить файл Excel с помощью FastAPI?

Сообщение Anonymous »

Как вернуть файл Excel (версия: Office365) с помощью FastAPI? Документация кажется довольно простой. Но я не знаю, какой media_type использовать. Вот мой код:
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'
)

Предполагая, что я все понял правильно, как скачать файл? Могу ли я использовать пользовательский интерфейс Swagger, созданный FastAPI, для просмотра листа? Или завиток? В идеале я хотел бы иметь возможность загружать и просматривать файл в Excel.
Решение
Вот мое окончательное (отредактированное) решение, которое избавит вас от необходимости нажимать на ссылку. В ходе разработки мне пришлось переключиться с FileResponse на Response, который возвращает io.BytesIO.
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
)


Подробнее здесь: https://stackoverflow.com/questions/720 ... ng-fastapi
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»