29 Pandas和Flask配合实现快速在网页上展示表格数据
主程序
from flask import Flask, render_template
import pandas as pd
app = Flask(__name__)
def read_data():
return pd.read_csv("../datas/movielens-1m/users.dat",
sep="::",
engine="python",
header=None,
names="UserID::Gender::Age::Occupation::Zip-code".split("::")
)
@app.route('/get_user_info')
def get_user_info():
df = read_data()
df_male = df[df["Gender"] == "M"].head()
df_female = df[df["Gender"] == "F"].head()
return render_template(
"user_info.html",
male_data=df_male.to_html(classes="male", index=False),
female_data=df_female.to_html(classes="female", index=False)
)
if __name__ == '__main__':
app.run(
debug=True
)
模版
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户信息展示</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>用户信息展示</h1>
<h2>男性用户列表:</h2>
{{ male_data|safe }}
<h2>女性用户列表:</h2>
{{ female_data|safe }}
</body>
</html>
样式
padding: 20px;
}
a, h1, h2 {
color: #377ba8;
}
h1 {
border-bottom: 2px solid #eee;
}
h2 {
font-size: 1.2em;
}
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;
}
.male th {
background-color: #add8e6;
color: white;
}
.female th {
background-color: #77dd77;
color: white;
}
tr:nth-child(odd) {
background-color: #eee;
}
tr:nth-child(even) {
background-color: #fff;
}
tr:hover {
background-color: #ffff99;
}
本文使用 文章同步助手 同步
网友评论