我正在使用 FastAPI,目前我返回一个 csv,这是我用 pandas 从 SQL Server 读取的。 (pd.read_sql())
然而,csv 对于浏览器来说相当大,我想用文件响应返回它:https://fastapi.tiangolo.com/advanced/custom-response/ https://fastapi.tiangolo.com/advanced/custom-response/(本页末尾)。
如果不先将其写入 csv 文件,我似乎无法做到这一点,这看起来很慢,并且会在每个请求上用 csv 弄乱文件系统。
所以我的问题是,有没有办法从 sql 数据库或 pandas 数据帧返回 FileResponse。
如果没有,有没有办法在客户端读取完生成的 csv 文件后将其删除?
感谢您的帮助!
亲切的问候,
Stephan
很大程度上基于此https://github.com/tiangolo/fastapi/issues/1277 https://github.com/tiangolo/fastapi/issues/1277
- 将数据帧转换为流
- 使用流响应
- 修改标题以便下载(可选)
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import io
import pandas as pd
app = FastAPI()
@app.get("/get_csv")
async def get_csv():
df = pd.DataFrame(dict(col1 = 1, col2 = 2), index=[0])
stream = io.StringIO()
df.to_csv(stream, index = False)
response = StreamingResponse(iter([stream.getvalue()]),
media_type="text/csv"
)
response.headers["Content-Disposition"] = "attachment; filename=export.csv"
return response
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)