store views on the shouts table, remove the viewed table

This commit is contained in:
Alexey Kulikov
2023-07-30 23:57:31 +01:00
parent 18e5cd4747
commit 41055d8501
6 changed files with 14 additions and 101 deletions

View File

@@ -11,7 +11,6 @@ from sqlalchemy import func
from base.orm import local_session
from orm import User, Topic
from orm.shout import ShoutTopic, Shout
from orm.viewed import ViewedEntry
load_facts = gql("""
query getDomains {
@@ -128,10 +127,7 @@ class ViewedStorage:
with local_session() as session:
try:
shout = session.query(Shout).where(Shout.slug == shout_slug).one()
shout_views = session.query(func.sum(ViewedEntry.amount)).where(
ViewedEntry.shout == shout.id
).all()[0][0]
self.by_shouts[shout_slug] = shout_views
self.by_shouts[shout_slug] = shout.views
self.update_topics(session, shout_slug)
except Exception as e:
raise e
@@ -160,37 +156,17 @@ class ViewedStorage:
self.by_topics[topic.slug][shout_slug] = self.by_shouts[shout_slug]
@staticmethod
async def increment(shout_slug, amount=1, viewer='anonymous'):
async def increment(shout_slug, amount=1):
""" the only way to change views counter """
self = ViewedStorage
async with self.lock:
# TODO optimize, currenty we execute 1 DB transaction per shout
with local_session() as session:
# TODO: user slug -> id
viewed = session.query(
ViewedEntry
).join(
Shout, Shout.id == ViewedEntry.shout
).join(
User, User.id == ViewedEntry.viewer
).filter(
User.slug == viewer,
Shout.slug == shout_slug
).first()
if viewed:
viewed.amount = amount
print("amount: %d" % amount)
else:
shout = session.query(Shout).where(Shout.slug == shout_slug).one()
viewer = session.query(User).where(User.slug == viewer).one()
new_viewed = ViewedEntry.create(**{
"viewer": viewer.id,
"shout": shout.id,
"amount": amount
})
session.add(new_viewed)
shout = session.query(Shout).where(Shout.slug == shout_slug).one()
shout.views += amount
session.commit()
# this part is currently unused
self.by_shouts[shout_slug] = self.by_shouts.get(shout_slug, 0) + amount
self.update_topics(session, shout_slug)