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

22,553

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"})
Share:
22,553

Related videos on Youtube

swidnikk
Author by

swidnikk

Updated on September 06, 2020

Comments

  • swidnikk
    swidnikk over 3 years

    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?

  • swidnikk
    swidnikk over 11 years
    I have no idea what cell for row in results... is doing, can you explain?
  • Sean Vieira
    Sean Vieira over 11 years
    @swidnikk - that is a generator expression - it is like the list comprehension expression [x for x in range(10)] except it produces a generator object rather than a list. (x for x in range(10)) does not generate the whole list at once. Instead it lazily evaluates the next value of x each time __next__ (next in Python 2.X) is called. The docs show you a different way of creating generators using yield (def generator_func(): for x in range(10): yield x) The nested for expressions are there because I assumed a list of lists type of data structure. Does that make sense?
  • swidnikk
    swidnikk over 11 years
    Thanks. I wasn't sure how to look it up for more information. I understand now and found it in the docs here: docs.python.org/tutorial/classes.html#generators I suppose this will be especially useful if the file I'm creating becomes too large to keep in memory.