Add /user_acitivity

This commit is contained in:
hok7z 2022-12-21 22:37:54 +02:00
parent 2afc19f05d
commit add2351bee
1 changed files with 58 additions and 1 deletions

View File

@ -1,4 +1,6 @@
from flask import Blueprint, jsonify, request
from flask import Blueprint
from flask import request, jsonify
from peewee import SQL, fn
from database import Message, Member
@ -87,3 +89,58 @@ def chat_activity():
"date": dates,
"counts": counts
})
@group_stat_api.route("/user_activity", methods=["GET"])
def user_activity():
dates = []
counts = []
user_id = request.args.get("user_id")
user = Member.get_or_none(Member.user_id == user_id)
if not user:
return jsonify({
"err":"invalid user_id"
}),422
from_date = request.args.get("from_date")
to_date = request.args.get("to_date")
if not from_date or not to_date:
return jsonify({
"err": "from_date/to_date empty"
}),422
group_by = request.args.get("group_by")
group_by = group_by if group_by else "day"
date_format = request.args.get("date_format")
date_format = date_format if date_format else "%Y-%m-%d"
try:
from_date = datetime.strptime(from_date,date_format)
to_date = datetime.strptime(to_date, date_format)
except ValueError:
return jsonify({
"from_date": from_date,
"to_date": to_date,
"date_format": date_format,
"err":"can't format datatime obj"
}),422
query = (Message
.select( fn.date_trunc(group_by, Message.timestamp).alias("range"), fn.count(Message.id).alias("count") )
.where((Message.user == user) & (Message.timestamp >= from_date) & (Message.timestamp <= to_date))
.group_by(fn.date_trunc(group_by, Message.timestamp))
.order_by(SQL("range"))
)
for row in query:
dates.append(row.range.strftime(date_format))
counts.append(row.count)
return jsonify({
"date": dates,
"counts": counts
})