python-3.x - 如何使用烧瓶将 CSV 数据显示为 html 页面上的表格视图?
问题描述
我正在使用 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
如何使用烧瓶将上述数据显示为 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 的网页。有人可以帮忙吗?
输出:
先感谢您!
解决方案
在 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])
推荐阅读
- laravel - 我想从查询结果中检索 id 并将其重用于下一个查询 laravel
- laravel - 如何在 Laravel 中将验证错误闪现到会话
- protractor - element.getAttribute('value') 在量角器中返回 null
- angular - 如何更新动态创建的 Angular Material 组件的属性绑定(例如 ProgressBar 或 Spinner)
- javascript - Webpack ProvidePlugin 无法解析我的模块的绝对路径
- linkerd - 使用 linkerd 和 argo 推出的 Canary 推出
- android - Kotlin & Android Studio - 未解决的参考:FirebaseInstanceId
- google-sheets - 创建自动更新的 Google 表格
- google-chrome - 如何访问有关 Google Chrome 无法加载 PDF 的调试信息?
- c++ - 如何使指针成员 const'able