Rohan Kumar
Rohan Kumar

Reputation: 191

Write data to a CSV on the fly and download the file using fast api

I am getting corrupted data when I am downloading the file using the 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()

Downloading file using FileResponse:

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

Upvotes: 2

Views: 3214

Answers (1)

dukkee
dukkee

Reputation: 1122

No need to save the file locally, you can save it on the fly with help of StringIO/BytesIO. Personally, I recommend you to use CSV instead of XLSX format in such case, it will work faster.

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)

Upvotes: 3

Related Questions