首页 > 解决方案 > 如何在烧瓶python中将“新的csv文件”保存到“文件名”中

问题描述

我想保存result.csvfilename,以便它可以传递到HTML 页面app.config['UPLOAD_FOLDER']并从中检索download button,我应该对我的代码做什么?你们能分享一些关于我的代码的提示吗?在此先感谢

应用程序.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 页面>><a href="{{ url_for('download', filename=filename) }}">Download</a>

标签: pythonflaskwebredirectpath

解决方案


我不知道您是否设法解决了您的问题,但这是一种简单且易于实施的解决方案。

如果您已经有一个 .csv 文件,并且您想通过按一个按钮来下载它:

# 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)

并在表单部分的 html 中:

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

旁注:如果您在 Windows 中运行程序,则需要以管理员身份从命令 bash 运行它,否则您将遇到一些其他问题。我希望它有效。


推荐阅读