使用flask在同一HTML页面上返回带有下载选项的响应 [英] Return a response with an download option on the same HTML page using flask
问题描述
我有一个基本的flask应用程序,其中的数据帧是由两个CSV形成的,并且进行了一些转换,并且在HTML页面上,可以表格格式查看最终结果数据帧.到这里为止都很好.
I have a basic flask app where data frames are formed from two CSVs and some transformations happen and on the HTML page , a final result dataframe can be seen in a tabular format. It works fine till here.
除此之外,我还希望用户可以选择下载与CSV相同的表.
Apart from that, I also want the user to have an option to download the same table as a CSV.
下面是我的烧瓶代码:
from flask import *
import pandas as pd
app = Flask(__name__)
@app.route("/tables")
def show_tables():
df1 = pd.read_csv('daily.csv')
df2 = pd.read_csv('companies.csv')
df1['date']= pd.to_datetime(df1['date'], format='%m/%d/%y')
df3 = pd.merge(df1,df2,how='left',on='id')
dates = pd.DataFrame({"date": pd.date_range("2017-01-01", "2017-01-10")})
df4 = (df3.groupby(['id', 'name'])['date', 'value']
.apply(lambda g: g.merge(dates, how="outer"))
.fillna(0)
.reset_index(level=[0,1])
.reset_index(drop=True))
df4 = df4.sort_values(by=['id','date'])
df4.value = df4.value.astype(int)
df4['difference'] = df4.groupby('id')['value'].diff()
return render_template('view.html',tables=[df4.to_html(classes='Company_data')],
titles = [ 'Company_data'],filename=df4.to_csv())
@app.route('/tables_download/<filename>')
def tables_download(filename):
return response(filename) //--right way to pass the csv file?
if __name__ == "__main__":
app.run()
下面是我的 HTML 代码:
<!doctype html>
<title>Simple tables</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
<h1>Company data</h1>
{% for table in tables %}
<h2>{{titles[loop.index]}}</h2>
{{ table|safe }}
{% endfor %}
</div>
<a href="{{ url_for('tables_download', filename=filename) }}">Download</a>
在我的HTML页面上,我什至没有看到下载选项.
On my HTML page, I don't even see the Download option.
努力找出问题所在,因此寻求帮助
Struggling to figure out what's wrong so looking for help
推荐答案
正如Flask API中记录的那样,我相信send_file
或send_from_directory
将是实现此目的的方式.
As documented in the Flask API, I believe that send_file
or send_from_directory
would be the way to implement this.
@app.route('/uploads/<path:filename>')
def download_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
这些文件都记录在 http://flask.pocoo.org/docs/0.12上/api/
send_from_directory
更加安全(如果使用正确),因为它将可下载的文件限制为特定目录中的文件,从而防止任何黑客"下载您的私人信息.
send_from_directory
is more secure (if used correctly) as it limits the file available to download to just those in a specific directory preventing any 'hackers' from downloading your private information.
这篇关于使用flask在同一HTML页面上返回带有下载选项的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!