python - 如何在烧瓶python中将“新的csv文件”保存到“文件名”中
问题描述
我想保存result.csv
到filename
,以便它可以传递到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>
解决方案
我不知道您是否设法解决了您的问题,但这是一种简单且易于实施的解决方案。
如果您已经有一个 .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 运行它,否则您将遇到一些其他问题。我希望它有效。
推荐阅读
- haskell - Haskell - 将玫瑰树的深度优先遍历表示为展开的实例,以代数方式推导它
- python - 如何正确连接python中的两个函数?
- powershell - 按数字前导数对文件版本进行排序
- c# - 按日期更改一行代码?
- wordpress - wordpress 4.9.6 可视化编辑器添加跨度代码
- vue.js - 我如何填充 axios 获取数据数组并将其传递给 Vuejs 组件道具以在组件中进行列表渲染
- postgresql - 我如何使用 pg_trgm 更允许
- r - 检查值是否在单独数据框的特定范围内
- sql - 对别名使用 Case 语句
- python - 卸载 pip 不使用的软件包