Python Flask send_file StringIO blank files

前端 未结 3 1670
無奈伤痛
無奈伤痛 2020-12-13 18:42

I\'m using python 3.5 and flask 0.10.1 and liking it, but having a bit of trouble with send_file. I ultimately want to process a pandas dataframe (from Form data, which is u

3条回答
  •  醉酒成梦
    2020-12-13 18:57

    The issue here is that in Python 3 you need to use StringIO with csv.write and send_file requires BytesIO, so you have to do both.

    @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'
        )
    

提交回复
热议问题