24

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?

Paco
  • 4,520
  • 3
  • 29
  • 53
swidnikk
  • 546
  • 1
  • 3
  • 16

1 Answers1

41

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"})
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • 1
    I have no idea what cell for row in results... is doing, can you explain? – swidnikk Aug 29 '12 at 21:19
  • 1
    @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? – Sean Vieira Aug 29 '12 at 21:25
  • Thanks. I wasn't sure how to look it up for more information. I understand now and found it in the docs here: http://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. – swidnikk Aug 30 '12 at 14:18