【问题标题】:How to display CSV data as a table view on html page using flask?如何使用烧瓶将 CSV 数据显示为 html 页面上的表格视图?
【发布时间】:2020-08-20 19:55:14
【问题描述】:

我正在使用 Python 3.7.7 并从事以下工作:

我有一个目录,其中包含每天在此文件夹中创建的 csv 文件:

daily-2020-08-19.csv
daily-2020-08-18.csv
daily-2020-08-17.csv
... and so on...

我的数据文件的结构是按客户排序的:

daily-2020-08-17.csv
userId, calls, customers, emails
  2       0       11        30
  1       1       5         11
  3       11      0         0
    daily-2020-08-18.csv
userId, calls, customers, emails
  1       11      15       5
  2       0       2        5
  3       1       1        1
  5       0       1        1
  4       0       0        0
daily-2020-08-19.csv
userId, calls, customers, emails
  2       13      30       55
  1       11      15       5
  5       3       3        5
  3       2       2        1
  4       1       1        3
  7       1       1        1
  6       10      0        5

userId = 给定日期的活跃用户数。随着时间的推移,随着每天都有新用户注册,预计 ID 数量会增加。

我已经设法使用 pandas 对过去 3 天的数据求和,现在我有 3days.csv:

userId, customers
  2        43
  1        35
  5        4
  3        3
  4        1
  7        1
  6        0

如何使用flask将上述数据显示为html页面上的表格视图?我对烧瓶完全陌生,并且旨在让 userId 在我的表格中显示为 URL,然后将我带到特定于该特定 userID 的单独 html 页面。

到目前为止我的代码:

from flask import Flask
import os

app = Flask (__name__)

#fun var

filepath = os.path.join(os.path.dirname(__file__),'path/to/my/3days.csv')

open_read = open(filepath,'r')
page =''

while True:
    read_data = open_read.readline()
    page += '<p>%s</p>' % read_data
    if open_read.readline() == '':
        break

@app.route("/")
def index():
    return page


if __name__ == "__main__":
    app.run()

通过上面的代码,我设法只从我的 3days.csv 中获取了一些值。但是,我需要一个带有 userId 作为 URL 的表格视图,它可以将网页带到专用于特定 userId 的网页。有人可以帮忙吗?

输出:

提前谢谢你!

【问题讨论】:

    标签: python-3.x flask


    【解决方案1】:

    在table_page.html中:

    <table>
    {% for a_user in page %}
      <tr>
        <td><a href="{% url_for 'user_page', a_user.userId %}">User# {{ a_user.userId }}</a></td>
        <td>{{ a_user.customers }}</td>
      </tr>
    {% endfor %}
    </table>
    

    在views.py中:

    @app.route("/")
    def index():
        # page need to be a list, like [{'userId': '2', 'customers': '43'},{'userId': '1', 'customers': '35'}, ...]
        return render_template("table_page.html", page=page)
    

    然后制作一个用户页面:

    @app.route('user_page/<id>')
    def user_page(id=None):
      ....
    

    要将3days.csv 转换为page 列表(假设它是字符串变量而不是csv 文件。如果是csv 文件,则需要file.read() 它):

    pages = []
    lines =  3days_text.split('\n')
    
    for line in lines:
      line_as_list = line.split(",")
      pages.append({'userId': line_as_list[0], 'customers': line_as_list[1])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多