0

I am want to save result.csv into filename so that it can be passed to app.config['UPLOAD_FOLDER'] and retrieve back from a download button in HTML page, What should I do to my code? can you guys share me some tips regarding my code~ thanks in advance

app.py

UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__))
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/transform', methods=["POST"])
def transform_view():
.........
........
for i in range(X_FUTURE):
            curr_date = curr_date +  relativedelta(months=+1)
            dicts.append({'Predictions': transform[i], "Month": curr_date})
            

        new_data = pd.DataFrame(dicts).set_index("Month")
        ##df_predict = pd.DataFrame(transform, columns=["predicted value"])

        new_data.to_csv(os.path.join(app.config['UPLOAD_FOLDER'], "result.csv"), index = True, encoding='utf8')

        labels = [d['Month'] for d in dicts]
            
        values = [d['Predictions'] for d in dicts]

        colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                       "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                       "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

        line_labels=labels
        line_values=values
        return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values)

@app.route('/download/<filename>')
def download(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment = True)

HTML pgae>> <a href="{{ url_for('download', filename=filename) }}">Download</a>

Infinity
  • 1
  • 2

1 Answers1

0

I don't know if you managed to solve your problem, but here's one solution which is simple, and easy to implement.

If you already have a .csv file, and you want to download it by pressing a button:

# Make sure you add this library among the others that you have already
from flask import send_file.

# I also add the GET method (I usually get some errors if I don't include both)

@app.route('/transform', methods = ['GET','POST'])
def transform_view():
......
......
# Whatever code you are using to generate the .csv file
......
......

if request.form.get('save') == 'save':
        return send_file('name_of_your_file.csv', mimetype = 'csv', download_name = 'whatever_name_you_want.csv', as_attachment = True)

and in your html in the form section:

<form method='POST'>
    <input type="submit" name="save" value="save">
</form>

Side note: If you are running your program in windows, you need to run it from command bash as administrator, otherwise you are going to run into some other issues. I hope it works.

Eduardo
  • 45
  • 9