如何使用下载按钮从烧瓶应用程序下载熊猫或html表
我有一个烧瓶应用程序,要求用户上传CSV文件。然后进行一些计算,并在网页上返回表。我希望用户可以通过按下按钮下载表。 (熊猫或html表)
方
from flask import Flask, make_response, request, render_template
import pandas as pd
from werkzeug.utils import secure_filename
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *
from flask import send_file
from dominate.tags import img
import requests
import json
import numpy as np
import pytest
app = Flask(__name__)
Bootstrap(app)
@app.route('/')
def form():
return render_template('index.html')
@app.route('/barrPath', methods=["POST"])
def barrPath_view():
if request.method == 'POST':
# data_file is the name of the file upload field
f = request.files['data_file']
# for security - stops a hacker e.g. trying to overwrite system files
filename = secure_filename(f.filename)
# save a copy of the uploaded file
f.save(filename)
# Do some processing
df = barrdf(filename)
df_predictions = barr_Process(df)
df_predictions = barrAlgo(df_predictions, filename)
# dl_and_table(df_predictions, filename)
return render_template('table_viewer.html', tables=[df_predictions[1].to_html(classes='table table-striped')],
titles=df_predictions[1].columns.values)
def barrdf(filename):
df = pd.read_csv(filename)
df.style.set_table_styles([{'selector': '',
'props': [('border',
'10px solid yellow')]}])
return df
def barr_Process(df):
# Do a load of predictions
df_predictions=df
return df_predictions
def barrAlgo(df_predictions, filename):
#Do a whole load more processing
df_predictions =df_predictions
return df_predictions
#@app.route('/barrPathPredict', methods=["POST"])
# def PathPredict(df_predictions):
# return send_file(df_predictions,
# mimetype='"text/csv"',
# as_attachment=True,
# attachment_filename="My_predictions"
# )
if __name__ == '__main__':
app.run("0.0.0.0", port=8080, debug=True)
我在尝试了解如何下载输出的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table view</title>
</head>
<style>
table.dataframe, .dataframe th, .dataframe td {
border: none;
border-bottom: 1px solid #C8C8C8;
border-collapse: collapse;
text-align:left;
padding: 10px;
margin-bottom: 40px;
font-size: 0.9em;
max-width: 150px;
}
</style>
<body>
{% extends "layout.html" %}
{% block content %}
<div class="inner">
<form action="/barrPathPredict" method="post" enctype="multipart/form-data">
<input type="submit" value="Download"/>
</form>
</div>
{% for table in tables %}
{{titles[loop.index]}}
{{ table|safe }}
{% endfor %}
{% endblock %}
</body>
</html>
表 可以在@app.route中看到('/barrpathpredict'
,我试图返回表,但我认为原始熊猫不在范围内。我如何下载返回的html表或df_predictions
来自@app.route('/barrPath'
)
I have a flask app which asks a user to upload a csv file. It then does some calculations and returns a table on a web page. I would like the user to then be able to download the table by pressing a button.
I am having great trouble trying to understand how to download the outputted table (either the panda or the html table):
Here is my code:
from flask import Flask, make_response, request, render_template
import pandas as pd
from werkzeug.utils import secure_filename
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *
from flask import send_file
from dominate.tags import img
import requests
import json
import numpy as np
import pytest
app = Flask(__name__)
Bootstrap(app)
@app.route('/')
def form():
return render_template('index.html')
@app.route('/barrPath', methods=["POST"])
def barrPath_view():
if request.method == 'POST':
# data_file is the name of the file upload field
f = request.files['data_file']
# for security - stops a hacker e.g. trying to overwrite system files
filename = secure_filename(f.filename)
# save a copy of the uploaded file
f.save(filename)
# Do some processing
df = barrdf(filename)
df_predictions = barr_Process(df)
df_predictions = barrAlgo(df_predictions, filename)
# dl_and_table(df_predictions, filename)
return render_template('table_viewer.html', tables=[df_predictions[1].to_html(classes='table table-striped')],
titles=df_predictions[1].columns.values)
def barrdf(filename):
df = pd.read_csv(filename)
df.style.set_table_styles([{'selector': '',
'props': [('border',
'10px solid yellow')]}])
return df
def barr_Process(df):
# Do a load of predictions
df_predictions=df
return df_predictions
def barrAlgo(df_predictions, filename):
#Do a whole load more processing
df_predictions =df_predictions
return df_predictions
#@app.route('/barrPathPredict', methods=["POST"])
# def PathPredict(df_predictions):
# return send_file(df_predictions,
# mimetype='"text/csv"',
# as_attachment=True,
# attachment_filename="My_predictions"
# )
if __name__ == '__main__':
app.run("0.0.0.0", port=8080, debug=True)
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table view</title>
</head>
<style>
table.dataframe, .dataframe th, .dataframe td {
border: none;
border-bottom: 1px solid #C8C8C8;
border-collapse: collapse;
text-align:left;
padding: 10px;
margin-bottom: 40px;
font-size: 0.9em;
max-width: 150px;
}
</style>
<body>
{% extends "layout.html" %}
{% block content %}
<div class="inner">
<form action="/barrPathPredict" method="post" enctype="multipart/form-data">
<input type="submit" value="Download"/>
</form>
</div>
{% for table in tables %}
{{titles[loop.index]}}
{{ table|safe }}
{% endfor %}
{% endblock %}
</body>
</html>
As you can see in the @app.route('/barrPathPredict'
, I have tried to return the table but I think the original panda is out of scope. How can I download the returned html table or the df_predictions
from the @app.route('/barrPath'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在这里看到了一些选项:
您在
barrpath_view
中呈现html中的表,因此用户可以使用“保存页面为“浏览器”功能。我不确定是否可以从页面上的JavaScript中触发。如果您需要这样的按钮,则可以使用
pandas.dataframe.to_html
( https://pandas.pydata.org/docs/reference/reference/api/pandas.dataframe.to_html.html )可生成可下载的内容和:将其保存在临时文件中,然后添加路由以下载该文件。在这种情况下,需要以某种方式对服务器端存储进行管理。
将其推向JavaScript变量中的客户端,并允许以文件为文件,如下所示 - 如何将JavaScript数组信息导出到CSV(在客户端上侧)?
您还可以通过JavaScript
DataTables渲染表格/buttons/examples/initialisation/export.html“ rel =” nofollow noreferrer“> https://datatables.net/extensions/buttons/examples/initialisation/export.html )
I see few options here:
you are rendering the table in HTML in
barrPath_view
, so user is able to use "Save page as" browser feature. I'm not sure if this can be triggered from within the javascript on the page.if you need such button, you can use
pandas.DataFrame.to_html
(https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html) to generate downloadable content and:save it on the server in temporary file and add route to download such file. The server-side storage needs to be managed somehow in this case.
push it to the client in javascript variable, and allow to be donwloaded as file as shown here -- How to export JavaScript array info to csv (on client side)?
you can also render your table via javascript
DataTables
which does haveExport file
functionality built-in (https://datatables.net/extensions/buttons/examples/initialisation/export.html)