core/services/stat/topicstat.py

63 lines
2.1 KiB
Python
Raw Normal View History

import asyncio
2022-08-11 05:53:14 +00:00
from base.orm import local_session
2022-09-19 13:50:43 +00:00
from orm.shout import Shout, ShoutTopic
from orm.topic import TopicFollower
2022-08-11 09:09:57 +00:00
from services.zine.shoutauthor import ShoutAuthorStorage
2022-09-07 19:36:40 +00:00
class TopicStat:
2022-10-03 21:45:26 +00:00
# by slugs
2022-09-19 13:50:43 +00:00
shouts_by_topic = {} # Shout object stored
authors_by_topic = {} # User
followers_by_topic = {} # User
2022-10-03 21:45:26 +00:00
#
2022-09-03 10:50:14 +00:00
lock = asyncio.Lock()
period = 30 * 60 # sec
2022-09-03 10:50:14 +00:00
@staticmethod
async def load_stat(session):
self = TopicStat
shout_topics = session.query(ShoutTopic).all()
2022-11-17 06:25:26 +00:00
print("[stat.topics] %d links for shouts" % len(shout_topics))
2022-09-03 10:50:14 +00:00
for shout_topic in shout_topics:
2022-09-19 13:50:43 +00:00
tpc = shout_topic.topic
2022-09-14 13:02:05 +00:00
# shouts by topics
2022-09-19 13:50:43 +00:00
shout = session.query(Shout).where(Shout.slug == shout_topic.shout).first()
2022-10-03 21:45:26 +00:00
self.shouts_by_topic[tpc] = self.shouts_by_topic.get(tpc, dict())
self.shouts_by_topic[tpc][shout.slug] = shout
2022-09-14 13:02:05 +00:00
# authors by topics
2022-09-19 13:50:43 +00:00
authors = await ShoutAuthorStorage.get_authors(shout.slug)
2022-10-03 21:45:26 +00:00
self.authors_by_topic[tpc] = self.authors_by_topic.get(tpc, dict())
2022-09-19 13:50:43 +00:00
for a in authors:
2022-10-03 21:45:26 +00:00
[aslug, acaption] = a
self.authors_by_topic[tpc][aslug] = acaption
2022-09-14 13:02:05 +00:00
2022-09-03 10:50:14 +00:00
self.followers_by_topic = {}
2022-09-19 13:50:43 +00:00
followings = session.query(TopicFollower).all()
2022-11-17 06:25:26 +00:00
print("[stat.topics] %d followings by users" % len(followings))
2022-09-03 10:50:14 +00:00
for flw in followings:
topic = flw.topic
2022-10-03 21:45:26 +00:00
userslug = flw.follower
self.followers_by_topic[topic] = self.followers_by_topic.get(topic, dict())
self.followers_by_topic[topic][userslug] = userslug
2022-09-03 10:50:14 +00:00
@staticmethod
async def get_shouts(topic):
self = TopicStat
async with self.lock:
2022-10-03 21:45:26 +00:00
return self.shouts_by_topic.get(topic, dict())
2022-09-03 10:50:14 +00:00
@staticmethod
async def worker():
self = TopicStat
while True:
try:
with local_session() as session:
async with self.lock:
await self.load_stat(session)
except Exception as err:
2022-09-19 13:50:43 +00:00
raise Exception(err)
2022-09-03 10:50:14 +00:00
await asyncio.sleep(self.period)