如何使用下载按钮从烧瓶应用程序下载熊猫或html表

发布于 2025-02-12 09:56:34 字数 3325 浏览 1 评论 0原文

我有一个烧瓶应用程序,要求用户上传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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

可爱暴击 2025-02-19 09:56:35

我在这里看到了一些选项:

  • 您在barrpath_view中呈现html中的表,因此用户可以使用“保存页面为“浏览器”功能。我不确定是否可以从页面上的JavaScript中触发。

  • 如果您需要这样的按钮,则可以使用pandas.dataframe.to_html https://pandas.pydata.org/docs/reference/reference/api/pandas.dataframe.to_html.html )可生成可下载的内容和:

  • 您还可以通过JavaScript DataTables渲染表格/buttons/examples/initialisation/export.html“ rel =” nofollow noreferrer“> https://datatables.net/extensions/buttons/examples/initialisation/export.html )


I see few options here:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文