some fixes, schema update

This commit is contained in:
tonyrewin 2022-11-22 10:29:54 +03:00
parent 6c7e56909a
commit 835b51de36
3 changed files with 71 additions and 54 deletions

View File

@ -199,33 +199,13 @@ async def delete_reaction(_, info, rid):
return {} return {}
@query.field("loadReactionsBy") def prepare_reactions(q, by, user=None):
async def load_reactions_by(_, info, by, limit=50, offset=0): if by.get("shout"):
"""
:param by: {
shout: 'some-slug'
author: 'discours',
topic: 'culture',
body: 'something else',
stat: 'rating' | 'comments' | 'reacted' | 'views',
days: 30
}
:param limit: int amount of shouts
:param offset: int offset in this order
:return: Reaction[]
"""
q = select(Reaction).join(
Shout
).where(
Reaction.deletedAt.is_(None)
)
if by.get("slug"):
q = q.filter(Shout.slug == by["slug"]) q = q.filter(Shout.slug == by["slug"])
else: else:
if by.get("reacted"): if by.get("reacted"):
user = info.context["request"].user if user:
q = q.filter(Reaction.createdBy == user.slug) q = q.filter(Reaction.createdBy == user.slug)
if by.get("author"): if by.get("author"):
q = q.filter(Reaction.createdBy == by["author"]) q = q.filter(Reaction.createdBy == by["author"])
if by.get("topic"): if by.get("topic"):
@ -240,8 +220,40 @@ async def load_reactions_by(_, info, by, limit=50, offset=0):
q = q.filter(Reaction.createdAt > before) q = q.filter(Reaction.createdAt > before)
q = q.group_by(Reaction.id).order_by( q = q.group_by(Reaction.id).order_by(
desc(by.get("order") or Reaction.createdAt) desc(by.get("sort") or Reaction.createdAt)
).limit(limit).offset(offset) )
return q
@query.field("loadReactionsBy")
async def load_reactions_by(_, info, by, limit=50, offset=0):
"""
:param by: {
shout: 'some-slug'
author: 'discours',
topic: 'culture',
body: 'something else' | true,
sort: 'rating' | 'comments' | 'reacted' | 'views',
days: 30
}
:param limit: int amount of shouts
:param offset: int offset in this order
:return: Reaction[]
"""
user = None
try:
user = info.context["request"].user
except Exception:
pass
q = select(Reaction).join(
Shout,
Reaction.shout == Shout.slug
).where(
Reaction.deletedAt.is_(None)
)
q = prepare_reactions(q, by, user)
q = q.limit(limit).offset(offset)
rrr = [] rrr = []
with local_session() as session: with local_session() as session:

View File

@ -255,7 +255,7 @@ input ReactionBy {
author: String author: String
order: String order: String
days: Int days: Int
stat: String sort: String
} }
################################### Query ################################### Query

View File

@ -99,18 +99,20 @@ class ViewedStorage:
period = 24 * 60 * 60 # one time a day period = 24 * 60 * 60 # one time a day
client = None client = None
auth_result = None auth_result = None
disabled = False
@staticmethod @staticmethod
async def init(): async def init():
if token: self = ViewedStorage
self = ViewedStorage async with self.lock:
async with self.lock: if token:
self.client = create_client({ self.client = create_client({
"Authorization": "Bearer %s" % str(token) "Authorization": "Bearer %s" % str(token)
}, schema=schema_str) }, schema=schema_str)
print("[stat.viewed] authorized permanentely by ackee.discours.io: %s" % token) print("[stat.viewed] authorized permanentely by ackee.discours.io: %s" % token)
else: else:
print("[stat.viewed] please, set ACKEE_TOKEN") print("[stat.viewed] please set ACKEE_TOKEN")
self.disabled = True
@staticmethod @staticmethod
async def update(session): async def update(session):
@ -203,26 +205,29 @@ class ViewedStorage:
@staticmethod @staticmethod
async def worker(): async def worker():
self = ViewedStorage
failed = 0 failed = 0
while True: self = ViewedStorage
try: if self.disabled:
with local_session() as session: return
# await self.update(session) async with self.lock:
await self.update_pages(session) while True:
failed = 0 try:
except Exception: with local_session() as session:
failed += 1 # await self.update(session)
print("[stat.viewed] update failed #%d, wait 10 seconds" % failed) await self.update_pages(session)
if failed > 3: failed = 0
print("[stat.viewed] not trying to update anymore") except Exception:
break failed += 1
if failed == 0: print("[stat.viewed] update failed #%d, wait 10 seconds" % failed)
when = datetime.now(timezone.utc) + timedelta(seconds=self.period) if failed > 3:
t = format(when.astimezone().isoformat()) print("[stat.viewed] not trying to update anymore")
t = t.split("T")[0] + " " + t.split("T")[1].split(".")[0] break
print("[stat.viewed] next update: %s" % t) if failed == 0:
await asyncio.sleep(self.period) when = datetime.now(timezone.utc) + timedelta(seconds=self.period)
else: t = format(when.astimezone().isoformat())
await asyncio.sleep(10) t = t.split("T")[0] + " " + t.split("T")[1].split(".")[0]
print("[stat.viewed] trying to update data again...") print("[stat.viewed] next update: %s" % t)
await asyncio.sleep(self.period)
else:
await asyncio.sleep(10)
print("[stat.viewed] trying to update data again...")