Python Flask send_file StringIO empty files

I am using python 3.5 and flask 0.10.1 and love it, but have few problems with send_file. Ultimately, I want to process the pandas framework (from the form data, which is not used in this example, but is needed in the future) and send it for download as csv (without a temporary file). The best way to achieve this I have seen StringIO for us.

Here is the code I'm trying to use:

@app.route('/test_download', methods = ['POST'])
def test_download():
    buffer = StringIO()
    buffer.write('Just some letters.')
    buffer.seek(0)
    return send_file(buffer, as_attachment = True,\
    attachment_filename = 'a_file.txt', mimetype = 'text/csv')

Downloading a file with the appropriate name, but the file is completely empty.

Any ideas? Encoding problems? Did they get the answer elsewhere? Thank!

+18
source share
3 answers

, Python 3 StringIO csv.write, send_file BytesIO, .

@app.route('/test_download')
def test_download():
    row = ['hello', 'world']
    proxy = io.StringIO()

    writer = csv.writer(proxy)
    writer.writerow(row)

    # Creating the byteIO object from the StringIO Object
    mem = io.BytesIO()
    mem.write(proxy.getvalue().encode('utf-8'))
    # seeking was necessary. Python 3.5.2, Flask 0.12.2
    mem.seek(0)
    proxy.close()

    return send_file(
        mem,
        as_attachment=True,
        attachment_filename='test.csv',
        mimetype='text/csv'
    )
+25

, .

from io import BytesIO    

from flask import Flask, send_file


app = Flask(__name__)


@app.route('/test_download', methods=['POST'])
def test_download():
    # Use BytesIO instead of StringIO here.
    buffer = BytesIO()
    buffer.write(b'jJust some letters.')
    # Or you can encode it to bytes.
    # buffer.write('Just some letters.'.encode('utf-8'))
    buffer.seek(0)
    return send_file(buffer, as_attachment=True,
                     attachment_filename='a_file.txt',
                     mimetype='text/csv')


if __name__ == '__main__':
    app.run(debug=True)
+12

- python 2.7 Flask StringIO, . .

String IO, , : io import StringIO StringIO import StringIO.

io import BytesIO, .

0

All Articles