首页 > 解决方案 > 即时将数据写入 CSV 并使用快速 api 下载文件

问题描述

当我使用 api 下载文件时,我收到了损坏的数据:

file_name = 'download' 
prepared_df = pd.DataFrame.from_dict(data)
path_to_excel = os.path.join(dir_to_download, file_name)
writer = pd.ExcelWriter(path_to_excel, engine='xlsxwriter')
prepared_df.to_excel(writer, sheet_name="Sheet1", index=False)
writer.save()
writer.close()

使用下载文件FileResponse

FileResponse(path=path_to_excel, filename=file_name, media_type='text/xlsx')

标签: pythondataframefastapi

解决方案


无需在本地保存文件,您可以在StringIO/的帮助下即时保存BytesIO。就个人而言,我建议您在这种情况下使用 CSV 而不是 XLSX 格式,它会运行得更快。

from io import BytesIO

import pandas as pd
import uvicorn
from fastapi import FastAPI
from fastapi.responses import StreamingResponse


app = FastAPI()


@app.get("/file", response_description='xlsx')
async def xlsx_file():
    frame = pd.read_excel("filename.xlsx")
    output = BytesIO()

    with pd.ExcelWriter(output) as writer:
        frame.to_excel(writer)

    headers = {
        'Content-Disposition': 'attachment; filename="example.xlsx"'
    }
    return StreamingResponse(iter([output.getvalue()]), headers=headers)


if __name__ == '__main__':
    uvicorn.run(app)

推荐阅读