0

I have a python webservice that is suppose to receive a GET request from the browser, writes some data into a csv file and serves it back to the browser.

I am struggling with this last step. How can I serve the file back to the browser? Is there a way to do it without creating or keeping the csv file on the server?

@app.route('/', methods = ['GET'])
def get_file():

        alldata = []

        while len(new_data) > 0:
                new_data = api.timeline(max_id=oldest)
                alldata.extend(new_data)
                oldest = alldata[-1].id - 1    
        outdata = [[info.id_str] for data in alldata]

        #write the csv
        with open('data.csv', 'wb') as f:
                writer = csv.writer(f)
                writer.writerows(outdata)
        pass

if __name__ == '__main__':
  app.run(host = app.config['HOST'], port = app.config['PORT'])
1
  • 1
    You have to use a generator, as described in flask.pocoo.org/docs/0.10/patterns/streaming or you are using a StringIO (or one of the new classes in the io module in Python 3) instead of the file. Commented Apr 21, 2015 at 16:39

1 Answer 1

1

Instead of writing the file to disk, you can just return it like this:

from flask import make_response

outdata = ""

for data in alldata:
    outdata += ",".join(data) + "\n"

response = make_response(outdata)
response.headers["Content-Disposition"] = "attachment; filename=data.csv"

return response

Alternatively, if you do want to write the file to disk, you can use send_from_directory:

return send_from_directory('my_app', 'data.csv')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.