[Fixed]-How to generate a file without saving it to disk in python?

13👍

Thanks to @Ragora, you pointed me towards the right direction.

I rewrote the newcsv method:

from io import StringIO
import csv


def newcsv(data, csvheader, fieldnames):
    """
    Create a new csv file that represents generated data.
    """
    new_csvfile = StringIO.StringIO()
    wr = csv.writer(new_csvfile, quoting=csv.QUOTE_ALL)
    wr.writerow(csvheader)
    wr = csv.DictWriter(new_csvfile, fieldnames = fieldnames)

    for key in data.keys():
        wr.writerow(data[key])

    return new_csvfile

and in the admin:

csvfile = newcsv(data, csvheader, fieldnames)

response = HttpResponse(csvfile.getvalue(), content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=stock.csv'
return response

-2👍

If it annoys you that you are saving a file to disk, just add the application/octet-stream content-type to the Content-Disposition header then delete the file from disk.

If this header (Content-Disposition) is used in a response with the application/octet- stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as…’ dialog.

Leave a comment