gpt4 book ai didi

python - FastAPI,返回带有SQL查询输出的File响应

转载 作者:行者123 更新时间:2023-12-03 15:09:18 25 4
gpt4 key购买 nike

我正在使用FastAPI,目前返回一个csv,该数据是我从SQL Server读取的带有 Pandas 的。 (pd.read_sql())
但是,csv对于浏览器来说相当大,我想通过File响应将其返回:
https://fastapi.tiangolo.com/advanced/custom-response/(页面结尾)。
我似乎无法做到这一点,除非先将其写入一个看起来很慢的csv文件,并且每次请求时csv都会使文件系统困惑。

所以我的问题方式是,有没有办法从sql数据库或pandas数据帧返回FileResponse。

如果没有,在客户端读取所有生成的csv文件之后,是否有办法删除它们?

谢谢你的帮助!

亲切的问候,

史蒂芬(Stephan)

最佳答案

https://github.com/tiangolo/fastapi/issues/1277为基础

  • 将您的数据帧转换为流
  • 使用流式响应
  • 修改标题,以便下载(可选)

  •     from fastapi.responses StreamingResponse

    @app.get("/get_csv")
    async def get_csv():

    df = pandas.DataFrame(dict(col1 = 1, col2 = 2))

    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

    关于python - FastAPI,返回带有SQL查询输出的File响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61140398/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com