Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file, parse it and serve in Flask

Tags:

python

flask

I'm taking my first steps with Flask. I can successfuly download a file from a client and give it back with the code from here: http://flask.pocoo.org/docs/patterns/fileuploads/

But how to change it (eg. line after line) and then serve it to the client?

I can get the string with read() after:

if file and allowed_file(file.filename):

and then process it. So the question really is: how do I serve output string as a file?

I don't want to save it on a server's hdd at all (both original version and changed).

like image 366
Matthew Avatar asked Apr 26 '13 14:04

Matthew


People also ask

How do I download a CSV file by clicking a link in python Flask?

Firstly you need to import from flask make_response , that will generate your response and create variable, something like response . Secondly, make response. content_type = "text/csv" Thirdly - return your response. I used a different approach as answered.

How do I download multiple files from Flask?

In order to offer several files together as a download, you only have the option of compressing them in an archive. In my example, all files that match the specified pattern are listed and compressed in a zip archive. This is written to the memory and sent by the server. Save this answer.


1 Answers

You can use make_response to create the response for your string and add Content-Disposition: attachment; filename=anyNameHere.txt to it before returning it:

@app.route("/transform-file", methods=["POST"])
def transform():
    # Check for valid file and assign it to `inbound_file`
    data = inbound_file.read()
    data = data.replace("A", "Z")
    response = make_response(data)
    response.headers["Content-Disposition"] = "attachment; filename=outbound.txt"
    return response

See also: The docs on streaming content

like image 61
Sean Vieira Avatar answered Oct 14 '22 10:10

Sean Vieira