1

I have part of an API in Flask that currently returns a Numpy array in Json, I need to offer the option to return as a CSV rather than as Json.

The only way I have successfully done this is to save the Numpy array as a CSV using numpy.savetxt then serve that file. I have found I can not leave the file behind like this How can I generate file on the fly and delete it after download? however that still feels 'kludgy'

Is there a way to return a Numpy array as a CSV without going via the file?

Community
  • 1
  • 1
dom
  • 33
  • 5

2 Answers2

2

Yes you can,

@app.route('/download')
def download():
    csv = convert_numpy_array_to_csv(your_numpy_array)
    response = make_response(csv)
    response.headers["Content-Disposition"] = "attachment; filename=array.csv"
    return response

You don't have to save the csv to a file. In case you can't avoid creating files, you can create the files in your temp folders (could be obtained by import tempfile;tempfile.gettempdir()). Doing so would automatically remove the files every time your system is restarted

Ashoka Lella
  • 6,631
  • 1
  • 30
  • 39
  • 1
    Thanks for the answer - however the way I go from Numpy to csv (numpy.writetxt) only exports to a file. – dom Jun 27 '14 at 08:58
  • 1
    Thanks - I was using tempfile but didn't want to leave the files hanging around between reboots. – dom Jun 27 '14 at 15:03
1

Well, if you want to use the numpy.savetxt function, then you can just use cStringIO:

from cStringIO import StringIO
output = StringIO()
numpy.savetxt(output, numpy_array)
csv_string = output.getvalue()

For python 3 you would import StringIO or BytesIO from the io module instead.

dustyrockpyle
  • 3,184
  • 17
  • 12
  • 1
    This looks exactly like what I need. Will try and report back. – dom Jun 27 '14 at 14:41
  • 1
    This allowed me to create the CSV using savetxt and serve as required without going via a CSV. Thx! – dom Jun 27 '14 at 15:04