Как вернуть файл 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
Как вернуть и загрузить файл Excel с помощью FastAPI? ⇐ Python
Программы на Python
-
Anonymous
1730026691
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.
[b]Решение[/b]
Вот мое окончательное (отредактированное) решение, которое избавит вас от необходимости нажимать на ссылку. В ходе разработки мне пришлось переключиться с 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
)
Подробнее здесь: [url]https://stackoverflow.com/questions/72052908/how-to-return-and-download-excel-file-using-fastapi[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия