Directly download pandas dataframe

hello,friends. i have a file export page.

df = pd.DataFrame( list (result))

df.to_csv( src )

return response.file( src )

can i not save to disk directly download it

Do you want to save the file to the server, or are you trying to make an endpoint for the csv to be downloaded from your api?

thank you, i want make an endpoint for the csv to be downloaded from my api,

in flask, like this

    resp = make_response( export_phone() )

    resp.headers["Content-Disposition"] = "attachment; filename=phone.csv"

    resp.headers["Content-Type"] = "text/csv"

    return resp

but now, i have to save it to disk, then download it

async def export(request, tag): 

    if tag == "phone":                             

        filename  = 'phone.csv'

        src  = r'C:\Users\zx\Desktop\phone.csv'

        export_phone(src)

    return await response.file(src, mime_type="text/csv", filename=filename)

You have a couple choices, and I supposed it depends upon how big your file is.

Assuming your data is already concatenated with commas, you can just return it.

from sanic import HTTPResponse

@app.get("/foo.csv")
async def handler(request):
    return HTTPResponse("foo,bar", content_type="text/csv")

That really is no different than Flask at all.

Another option if you have a large amount of data is to stream the response.

@app.get("/foo.csv")
async def handler(request):
    response = await request.respond(content_type="text/csv")
    await response.send("foo,")
    await response.send("bar")
    await response.eof()
1 Like

thank you very muck, i use HTTPResponse return the file success

1 Like