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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With