![](/img/trans.png)
[英]How to pass pandas dataframe to button in web for download file(.csv or .xlsx) with flask, Python 2.7
[英]How can I set a "download as csv" button for a pandas dataframe with Flask?
我试图为我的熊猫数据框(作为 csv)设置一个下载按钮,但我没有取得任何成功。
下面是我的views.py的相关功能:
from flask import render_template, make_response
from flask import send_file
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import random
import seaborn as sns
@app.route("/jinja")
def jinja():
my_name = "Testes"
return render_template("/public/jinja.html", my_name=my_name)
@app.route("/about")
def about():
return render_template("/public/about.html")
#defining parameters
bast_param = [0,5] #ba prefix for below average student
avst_param = [5,7] #av prefix for average student
aast_param = [7,10] #aa prefix for above average student
min_bast = bast_param[0]
max_bast = bast_param[1]
min_avst = avst_param[0]
max_avst = avst_param[1]
min_aast = aast_param[0]
max_aast = aast_param[1]
@app.route("/")
def index():
#students quantities per parameter
bast_qtd = 5
avst_qtd = 3
aast_qtd = 8
st_total = bast_qtd + avst_qtd + aast_qtd
#Defining Subjects
subjects = ["Disciplina 1", "Disciplina 2", "Disciplina 3", "Disciplina 4", "Disciplina 5"]
students = []
#counter for students ids creation
i = 0
#counters and variable for grades creation
a = 0
b = 0
newgradeline = []
grade = []
#creating students and grades
while(i < st_total):
newstudent = random.randint(100000,199999)
#excluding duplicates
if newstudent not in students:
students.append(newstudent)
i = i+1
# In[3]:
#below averagge students
while (a < bast_qtd):
b = 0
newgradeline = []
grade.append(newgradeline)
while (b<len(subjects)):
gen_grade = round(random.uniform(bast_param[0],bast_param[1]),2)
newgradeline.append(gen_grade)
b = b+1
a = a +1
a = 0
#average students
while (a < avst_qtd):
b = 0
newgradeline = []
grade.append(newgradeline)
while (b<len(subjects)):
gen_grade = round(random.uniform(avst_param[0],avst_param[1]),2)
newgradeline.append(gen_grade)
b = b+1
a = a +1
a = 0
#above average students
while (a < aast_qtd):
b = 0
newgradeline = []
grade.append(newgradeline)
while (b<len(subjects)):
gen_grade = round(random.uniform(aast_param[0],aast_param[1]),2)
newgradeline.append(gen_grade)
b = b+1
a = a +1
# In[4]:
#generating table
simulation = pd.DataFrame (grade,index=students, columns=subjects)
return render_template('/public/index.html',table=simulation.to_html(),download_csv=simulation.to_csv(index=True, sep=";"))
@app.route("/parameters")
def parameters():
return render_template('/public/parameters.html', min_bast=min_bast, max_bast=max_bast, min_avst=min_avst,max_avst=max_avst, min_aast=min_aast, max_aast=max_aast)
这是 html 页面,我目前将 csv 作为文本显示在页面{{download_csv | safe}}
{{download_csv | safe}}
:
{% extends "/public/templates/public_template.html" %}
{% block title %}Simulador{% endblock%}
{% block main %}
<div class="container">
<div class="row">
<div class="col">
</br>
<h1>Simulador</h1>
<hr/>
{{table| safe}}
<br />
<a class="btn btn-primary" href="/" role="button">New simulation</a>
<a class="btn btn-primary" href="/parameters" role="button">Edit Parameters</a>
</div>
</div>
<div class="row">
<div class="col">
</br>
<hr/>
<h1>CSV File</h1>
{{download_csv | safe}}
</br></br>
<a class="btn btn-primary" href="" role="button">Download CSV</a>
<hr/>
</div>
</div>
</div>
{% endblock %}
但我想要这个按钮<a class="btn btn-primary" href="" role="button">Download CSV</a>
触发在@app.route("/") def index():
我的views.py
我知道我需要在我的 views.py 上设置一条新路线才能进行此下载,但我该怎么做?
目前您的按钮下载没有做任何事情。
1 - OnClick=someFunction()
添加OnClick=someFunction()
以便当用户单击它时, someFunction()
被执行。
<a class="btn btn-primary" onClick="someFunction()" href="" role="button">Download CSV</a>
2 - 在您的somFunction()
将网页重定向到您想要的路线,例如location.replace("/download");
function someFunction()
{
//..... You can here send user input from HTML to Flask through Ajax POST request if you wish.........//
location.replace("/download");
}
3 - 最后,在你的 Flask 中,确保你有一个/download
路径来处理 csv。
更新如果您不想使用 javascript 函数进行重定向,请尝试以下操作:
1 - 将您的 index() 路由更改为更明显的内容,例如@app.route("/download")
2 - 将下载 CSV 按钮的 href 分配给函数的路由
<a class="btn btn-primary" href="{{ url_for('index') }}" role="button">Download CSV</a>
我要做的是将模拟的创建移动到单独的函数 create_simulation() 并为下载创建一个新路由,如下所示:
from flask import render_template, make_response, Response
from flask import send_file
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import random
import seaborn as sns
@app.route("/jinja")
def jinja():
my_name = "Testes"
return render_template("/public/jinja.html", my_name=my_name)
@app.route("/about")
def about():
return render_template("/public/about.html")
#defining parameters
bast_param = [0,5] #ba prefix for below average student
avst_param = [5,7] #av prefix for average student
aast_param = [7,10] #aa prefix for above average student
min_bast = bast_param[0]
max_bast = bast_param[1]
min_avst = avst_param[0]
max_avst = avst_param[1]
min_aast = aast_param[0]
max_aast = aast_param[1]
@app.route("/")
def index():
simulation = create_simulation()
return render_template('/public/index.html',table=simulation.to_html(),download_csv=simulation.to_csv(index=True, sep=";"))
@app.route('/download')
def download():
# stream the response as the data is generated
response = Response(create_simulation(), mimetype='text/csv')
# add a filename
response.headers.set("Content-Disposition", "attachment", filename="simulation.csv")
return response
@app.route("/parameters")
def parameters():
return render_template('/public/parameters.html', min_bast=min_bast, max_bast=max_bast, min_avst=min_avst,max_avst=max_avst, min_aast=min_aast, max_aast=max_aast)
def create_simulation():
#students quantities per parameter
bast_qtd = 5
avst_qtd = 3
aast_qtd = 8
st_total = bast_qtd + avst_qtd + aast_qtd
#Defining Subjects
subjects = ["Disciplina 1", "Disciplina 2", "Disciplina 3", "Disciplina 4", "Disciplina 5"]
students = []
#counter for students ids creation
i = 0
#counters and variable for grades creation
a = 0
b = 0
newgradeline = []
grade = []
#creating students and grades
while(i < st_total):
newstudent = random.randint(100000,199999)
#excluding duplicates
if newstudent not in students:
students.append(newstudent)
i = i+1
# In[3]:
#below averagge students
while (a < bast_qtd):
b = 0
newgradeline = []
grade.append(newgradeline)
while (b<len(subjects)):
gen_grade = round(random.uniform(bast_param[0],bast_param[1]),2)
newgradeline.append(gen_grade)
b = b+1
a = a +1
a = 0
#average students
while (a < avst_qtd):
b = 0
newgradeline = []
grade.append(newgradeline)
while (b<len(subjects)):
gen_grade = round(random.uniform(avst_param[0],avst_param[1]),2)
newgradeline.append(gen_grade)
b = b+1
a = a +1
a = 0
#above average students
while (a < aast_qtd):
b = 0
newgradeline = []
grade.append(newgradeline)
while (b<len(subjects)):
gen_grade = round(random.uniform(aast_param[0],aast_param[1]),2)
newgradeline.append(gen_grade)
b = b+1
a = a +1
# In[4]:
#generating table
simulation = pd.DataFrame (grade,index=students, columns=subjects)
return simulation
然后你的 html 应该看起来像这样,我只将 href 更改为“/下载”:
{% extends "/public/templates/public_template.html" %}
{% block title %}Simulador{% endblock%}
{% block main %}
<div class="container">
<div class="row">
<div class="col">
</br>
<h1>Simulador</h1>
<hr/>
{{table| safe}}
<br />
<a class="btn btn-primary" href="/" role="button">New simulation</a>
<a class="btn btn-primary" href="/parameters" role="button">Edit Parameters</a>
</div>
</div>
<div class="row">
<div class="col">
</br>
<hr/>
<h1>CSV File</h1>
{{download_csv | safe}}
</br></br>
<a class="btn btn-primary" href="/download" role="button">Download CSV</a>
<hr/>
</div>
</div>
</div>
{% endblock %}
我基本上遵循了这个例子: Create and download a CSV file from a Flask view
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.