from flask import Blueprint, jsonify, request from peewee import SQL, fn from database import Message, Member from datetime import datetime group_stat_api = Blueprint('group_stat_api', __name__) @group_stat_api.route("/top_users", methods=["GET"]) def top_users(): number = request.args.get("number") if not number: number = 3 number = int(number) members = [] counts = [] query = (Member .select(fn.count(Message.id).alias("count"), Member) .join(Message) .group_by(Member) .order_by(SQL("count").desc()) ) for group in query: members.append(group.first_name) counts.append(group.count) members.insert(0, "Others") counts.insert(0, sum(counts[number:])) return jsonify({ "members": members[:number + 1], "counts": counts[:number + 1] }) @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") date_format = request.args.get("date_format") group_by = request.args.get("group_by") if not date_format: date_format = "%Y-%m-%d" if not group_by: group_by = "day" dates = [] counts = [] if from_date and to_date: from_date = datetime.strptime(from_date, date_format) to_date = datetime.strptime(to_date, date_format) query = (Message .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")) ) for group in query: dates.append(group.range.strftime("%Y-%m-%d")) counts.append(group.count) return jsonify({ "date": dates, "counts": counts })