randomTopics optimization
This commit is contained in:
parent
782c34a62b
commit
82be2da3d8
|
@ -1,14 +1,15 @@
|
||||||
import random
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy import and_, select
|
||||||
from sqlalchemy import and_
|
|
||||||
|
|
||||||
from auth.authenticate import login_required
|
from auth.authenticate import login_required
|
||||||
from base.orm import local_session
|
from base.orm import local_session
|
||||||
from base.resolvers import mutation, query
|
from base.resolvers import mutation, query
|
||||||
|
from orm import Shout
|
||||||
from orm.topic import Topic, TopicFollower
|
from orm.topic import Topic, TopicFollower
|
||||||
from services.zine.topics import TopicStorage
|
from services.zine.topics import TopicStorage
|
||||||
from services.stat.reacted import ReactedStorage
|
from services.stat.reacted import ReactedStorage
|
||||||
from services.stat.topicstat import TopicStat
|
from services.stat.topicstat import TopicStat
|
||||||
|
|
||||||
|
|
||||||
# from services.stat.viewed import ViewedStorage
|
# from services.stat.viewed import ViewedStorage
|
||||||
|
|
||||||
|
|
||||||
|
@ -98,10 +99,10 @@ async def topic_unfollow(user, slug):
|
||||||
with local_session() as session:
|
with local_session() as session:
|
||||||
sub = (
|
sub = (
|
||||||
session.query(TopicFollower)
|
session.query(TopicFollower)
|
||||||
.filter(
|
.filter(
|
||||||
and_(TopicFollower.follower == user.slug, TopicFollower.topic == slug)
|
and_(TopicFollower.follower == user.slug, TopicFollower.topic == slug)
|
||||||
)
|
)
|
||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
if not sub:
|
if not sub:
|
||||||
raise Exception("[resolvers.topics] follower not exist")
|
raise Exception("[resolvers.topics] follower not exist")
|
||||||
|
@ -113,11 +114,8 @@ async def topic_unfollow(user, slug):
|
||||||
|
|
||||||
@query.field("topicsRandom")
|
@query.field("topicsRandom")
|
||||||
async def topics_random(_, info, amount=12):
|
async def topics_random(_, info, amount=12):
|
||||||
topics = await TopicStorage.get_topics_all()
|
with local_session() as session:
|
||||||
normalized_topics = []
|
q = select(Topic).join(Shout).group_by(Topic.id).having(sa.func.count(Shout.id) > 2).order_by(
|
||||||
for topic in topics:
|
sa.func.random()).limit(amount)
|
||||||
topic.stat = await get_topic_stat(topic.slug)
|
random_topics = list(map(lambda result_item: result_item.Topic, session.execute(q)))
|
||||||
if topic.stat["shouts"] > 2:
|
return random_topics
|
||||||
normalized_topics.append(topic)
|
|
||||||
sample_length = min(len(normalized_topics), amount)
|
|
||||||
return random.sample(normalized_topics, sample_length)
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user