python - 即时将数据写入 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')
解决方案
无需在本地保存文件,您可以在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)
推荐阅读
- python - Raspberry Pi 服务器,显示位于单独 Html 文件中的表的问题
- python - 如何通过匹配每个“(a,b),(b,c),(c,d)”的第一个和最后一个值来对元组进行排序
- sublimetext3 - 我可以延迟 Pylint 在 Sublime Text 3 中保存时运行它吗?
- php - PHP制作占位符文件的子文件?
- php - Nginx 在响应数据之前添加来自其缓冲区的发布请求正文内容?
- c++ - Qt Checkable QActions
- reactjs - 嵌套路由和 Material-UI 列表不起作用
- java - 如何使用 Spring Security 和 Vue.js 设置登录?
- typescript - TypeScript 中的递归 AST 访问者
- python - 为什么这些自定义函数在 Python 中打印不同的值?