用户数据展示:
用户数据相关:
后端Flask代码:
from . import blue_admin
from flask import render_template, current_app
from info.models import User
import time
import datetime
@blue_admin.route("/user_count")
def user_count():
# 获取当前时间
now_time = time.localtime()
# 获取当前时间的年、月、日
now_year, now_month , now_day = now_time.tm_year, now_time.tm_mon, now_time.tm_mday
# 格式化时间, 此为每月第一天
month_time_str = "%d-%02d-01" % (now_year, now_month)
# 格式化时间, 此为当前年月日
day_time_str = "%d-%02d-%02d" % (now_year, now_month, now_day)
# 按 年-月-日 的格式转为datetime类型
now_datetime_month = datetime.datetime.strptime(month_time_str, "%Y-%m-%d")
# 按 年-月-日 的格式转为datetime类型
now_datetime_day = datetime.datetime.strptime(day_time_str, "%Y-%m-%d")
total_all = 0
month_all = 0
day_all = 0
x_data = []
y_data = []
# 取15天的数据
for i in range(0, 15):
# 开始日期, 起始0点
begin_time = now_datetime_day - datetime.timedelta(days=i)
# 结束日期, 结束0点
end_time = begin_time + datetime.timedelta(days=1)
# 按格式将日期转为字符串, 方便前端渲染
x_data.append(datetime.datetime.strftime(begin_time, "%m-%d"))
try:
# 查询对应时间段内用户的活跃量
y_data.append(User.query.filter(User.is_admin == False, User.last_login > begin_time, User.last_login < end_time).count())
except Exception as e:
current_app.logger.error(e)
# 反转列表
x_data.reverse()
y_data.reverse()
try:
# 查询所有非管理员用户数量
total_all = User.query.filter_by(is_admin=False).count()
# 查询所有月新增非管理员用户数量
month_all = User.query.filter(User.is_admin == False, User.create_time > now_datetime_month).count()
# 查询所有日新增非管理员用户数量
day_all = User.query.filter(User.is_admin == False, User.create_time > now_datetime_day, User.create_time < datetime.datetime.now()).count()
except Exception as e:
current_app.logger.error(e)
# 构造上下文
context = {
"total_all": total_all,
"month_all": month_all,
"day_all": day_all,
"x_data": x_data,
"y_data": y_data
}
# 返回页面与参数
return render_template("admin/user_count.html", context=context)
HTML代码:
新经资讯后台管理
当前位置:用户管理>用户统计
{{ context.total_all }}人
用户总数
{{ context.month_all }}人
用户月新增数
{{ context.day_all }}人
用户日新增数
Js代码: