Add /chat_activity

modified:   apps/group_stat_api.py
This commit is contained in:
hok7z 2022-12-17 11:58:53 +02:00
parent c413dbb577
commit ae466d53a4
1 changed files with 30 additions and 19 deletions

View File

@ -1,33 +1,44 @@
from flask import Blueprint, jsonify, request from flask import Blueprint, jsonify, request
from peewee import SQL, fn
from database import Message, Member from database import Message, Member
from datetime import datetime from datetime import datetime
group_stat_api = Blueprint('group_stat_api', __name__) group_stat_api = Blueprint('group_stat_api', __name__)
@group_stat_api.route("/chat_activity", methods=["GET"])
def chat_activity():
from_date = request.args.get("from_date")
to_date = request.args.get("to_date")
@group_stat_api.route("/top_users",methods=["GET"]) date_format = request.args.get("date_format")
def top_users(): group_by = request.args.get("group_by")
number = request.args.get("number")
if not number: number = 3 if not date_format:
date_format = "%Y-%m-%d"
number = int(number) if not group_by:
group_by = "day"
members = [] dates = []
counts = [] counts = []
for user in Member.select(): if from_date and to_date:
members.append(user.first_name) from_date = datetime.strptime(from_date, date_format)
counts.append(Message.select().where(Message.user_id == user.user_id).count()) to_date = datetime.strptime(to_date, date_format)
# Sorting query = (Message
counts, members = (list(t) for t in zip(*sorted(zip(counts,members),reverse=True))) .select(fn.date_trunc(group_by, Message.timestamp).alias('range'), fn.count(Message.id).alias('count'))
.where((Message.timestamp >= from_date) & (Message.timestamp <= to_date))
.group_by(fn.date_trunc(group_by, Message.timestamp))
.order_by(SQL("range"))
)
members.insert(number, "Others") for group in query:
counts.insert(number, sum(counts[number:])) dates.append(group.range.strftime("%Y-%m-%d"))
counts.append(group.count)
return jsonify({ return jsonify({
"members":members[:number+1], "date": dates,
"counts":counts[:number+1] "counts": counts
}) })