Download string as text file attachment in python Flask

Normally, we use send_file(path, as_attachment=True) to download a file as attachment. But, sometimes, the attachment's content is not in a file, but a static text or a dynamically built string.

An option is to save the text to a file and then use send_file. But this is not very elegant because a temporary file has to be involved.

A better option is to directly send the text as an attachment.

Code example for text file attachment

In this example, we download the text 'hello world' as an attachment named hello.txt.

from flask import Flask, Response

app = Flask(__name__)

@app.route('/download_txt')
def download_txt():
    return Response(
        'hello world',
        mimetype='text/plain',
        headers={'Content-disposition': 'attachment; filename=hello.txt'})

if __name__ == '__main__':
    app.run()

Note:

  • mimetype argument of Response should be set according to the file type. You can refer to Common MIME types.
  • Content-disposition header gives the file name and tells the browser that this is an attachment.

Code example for CSV file attachment

Another frequently used text file format is CSV. In the following example, we download the CSV content as an attachment named users.csv.

from flask import Flask, Response

app = Flask(__name__)

CSV_STR = '''id,name
0,user-0
1,user-1
2,user-2
3,user-3
4,user-4
'''

@app.route('/download_csv')
def download_csv():
    return Response(
        CSV_STR,
        mimetype='text/csv',
        headers={'Content-disposition': 'attachment; filename=users.csv'})

if __name__ == '__main__':
    app.run()
Posted on 2022-06-18