2
我有一個基本的燒瓶應用程序,其中數據框由兩個CSV形成,並且發生了一些轉換,並且在HTML頁面上可以看到最終結果數據框表格格式。它工作正常,直到這裏。使用燒瓶在同一個HTML頁面上下載選項返回響應
除此之外,我還希望用戶可以選擇下載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頁面,我甚至不看下載選項。
掙扎要弄清楚什麼是錯了,所以尋求幫助
很酷。所以,在我的情況下,我通過將數據幀轉換爲csv來立即生成文件。那麼,上傳文件夾應該是什麼? –
啊。我錯過了那部分。也許這[問題]的答案(http://stackoverflow.com/questions/30024948/flask-download-a-csv-file-on-clicking-a-button)將幫助你。 – scotty3785
或者[這個例子](http://code.runnable.com/UiIdhKohv5JQAAB6/how-to-download-a-file-generated-on-the-fly-in-flask-for-python) – scotty3785