Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

python - Send with multiple CSVs using Flask?

I have an app that takes in some information, performs some calculations using pandas, and turns the final pandas data frame into a CSV that is then downloaded using the Flask app. How do I download multiple CSVs within one view? It seems that I can only return a single response at a time.

An example snippet:

def serve_csv(dataframe,filename):
    buffer = StringIO.StringIO()
    dataframe.to_csv(buffer, encoding='utf-8', index=False)
    buffer.seek(0)
    return send_file(buffer,
             attachment_filename=filename,
             mimetype='text/csv')

def make_calculation(arg1, arg2):
   '''Does some calculations.
   input: arg1 - string, arg2- string
   returns: a pandas data frame'''

@app.route('test_app', methods=['GET', 'POST'])
def test_app():
    form = Form1()
    if form.validate_on_submit():
    calculated_dataframe = make_calculation(str(form.input_1.data), str(form.input_2.data))
        return serve_csv(calculated_dataframe, 'Your_final_output.csv')
    return render_template('test_app.html', form=form)

So let's say in that example above that make_calculation returned two pandas data frames. How would I print both of them to a CSV?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is all the code you need using the Zip files. It will return a zip file with all of your files.

In my program everything I want to zip is in an output folder so i just use os.walk and put it in the zip file with write. Before returning the file you need to close it, if you don't close it will return an empty file.

import zipfile
import os
from flask import send_file

@app.route('/download_all')
def download_all():
    zipf = zipfile.ZipFile('Name.zip','w', zipfile.ZIP_DEFLATED)
    for root,dirs, files in os.walk('output/'):
        for file in files:
            zipf.write('output/'+file)
    zipf.close()
    return send_file('Name.zip',
            mimetype = 'zip',
            attachment_filename= 'Name.zip',
            as_attachment = True)

In the html I simply call the route:

<a href="{{url_for( 'download_all')}}"> DOWNLOAD ALL </a>

I hope this helped somebody. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...