top_users write database

This commit is contained in:
hok7z 2022-12-14 16:12:57 +02:00
parent 3cb51c3fe0
commit 37851c5dc5
4 changed files with 37 additions and 18 deletions

View File

@ -1,12 +1,33 @@
from flask import Blueprint, jsonify from flask import Blueprint, jsonify, request
from database import Message, Member
from datetime import datetime
group_stat_api = Blueprint('group_stat_api', __name__) group_stat_api = Blueprint('group_stat_api', __name__)
@group_stat_api.route("/top3_users",methods=["POST"]) @group_stat_api.route("/top_users",methods=["GET"])
def top_users(): def top_users():
# TODO: database number = request.args.get("number")
if not number: number = 3
number = int(number)
members = []
counts = []
for user in Member.select():
members.append(user.first_name)
counts.append(Message.select().where(Message.user_id == user.user_id).count())
# Sorting
counts, members = (list(t) for t in zip(*sorted(zip(counts,members),reverse=True)))
members.insert(number, "Others")
counts.insert(number, sum(counts[number:]))
return jsonify({ return jsonify({
"members": ["Mr.D", "𝙲𝚊𝚝𝚒𝚘𝚗", "Тёма","Others"], "members":members[:number+1],
"counts":[4026,3024,2024,4096] "counts":counts[:number+1]
}) })

View File

@ -1,8 +1,7 @@
from peewee import Model, CharField, BigIntegerField, DateField, TimestampField from peewee import DateTimeField, ForeignKeyField, Model, CharField, BigIntegerField, DateField, TimestampField
from playhouse.db_url import connect from playhouse.db_url import connect
from datetime import date, datetime from datetime import date, datetime, timedelta
from config import db_url from config import db_url
db = connect(db_url) db = connect(db_url)
@ -32,12 +31,12 @@ class Member(Model):
class Message(Model): class Message(Model):
user_id = BigIntegerField() user_id = BigIntegerField()
timestamp = TimestampField(default=datetime.now()) first_name = CharField()
timestamp = DateTimeField(default=datetime.now())
class Meta: class Meta:
db_table = "messages" db_table = "messages"
database = db database = db
def build_database(): def build_database():
# db.create_tables([Message]) db.create_tables([WebUser,Message])
db.create_tables([WebUser])

View File

@ -1,9 +1,8 @@
const options = { fetch("/top_users?number=5", {
method: 'POST', // method: 'POST',
headers: {'Content-Type': 'application/json'} headers: {'Content-Type': 'application/json'}
} // body: JSON.stringify({number:5})
})
fetch("/top3_users", options)
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`); throw new Error(`HTTP error: ${response.status}`);