Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python using Flask, how can I write out an object for download?

Tags:

I'm using Flask and running foreman. I data that I've constructed in memory and I want the user to be able to download this data in a text file. I don't want write out the data to a file on the local disk and make that available for download.

I'm new to python. I thought I'd create some file object in memory and then set response header, maybe?

like image 817
swidnikk Avatar asked Aug 28 '12 20:08

swidnikk


People also ask

How do you create a object in a Flask?

Step 1 - Install the Flask-SQLAlchemy extension. Step 2 - You need to import the SQLAlchemy class from this module. Step 3 - Now create a Flask application object and set the URI for the database to use. Step 4 - then use the application object as a parameter to create an object of class SQLAlchemy.


1 Answers

Streaming files to the client without saving them to disk is covered in the "pattern" section of Flask's docs - specifically, in the section on streaming. Basically, what you do is return a fully-fledged Response object wrapping your iterator:

from flask import Response  # construct your app  @app.route("/get-file") def get_file():     results = generate_file_data()     generator = (cell for row in results                     for cell in row)      return Response(generator,                        mimetype="text/plain",                        headers={"Content-Disposition":                                     "attachment;filename=test.txt"}) 
like image 194
Sean Vieira Avatar answered Sep 23 '22 12:09

Sean Vieira