Files
core/orm/topic.py

72 lines
2.0 KiB
Python
Raw Normal View History

2021-08-20 11:08:32 +03:00
from datetime import datetime
from sqlalchemy import Table, Column, Integer, String, ForeignKey, DateTime, JSON as JSONType
2021-08-27 00:14:20 +03:00
from sqlalchemy.orm import relationship
2021-08-20 11:08:32 +03:00
from orm.base import Base
2021-12-12 16:00:38 +03:00
import asyncio
2021-10-28 13:42:34 +03:00
class TopicSubscription(Base):
2021-10-31 13:58:21 +03:00
__tablename__ = "topic_subscription"
2021-10-28 13:42:34 +03:00
id = None
topic = Column(ForeignKey('topic.slug'), primary_key = True)
2021-10-28 13:42:34 +03:00
user = Column(ForeignKey('user.id'), primary_key = True)
createdAt: str = Column(DateTime, nullable=False, default = datetime.now, comment="Created at")
2021-08-20 12:27:19 +03:00
2021-08-20 11:08:32 +03:00
class Topic(Base):
__tablename__ = 'topic'
id = None
slug: str = Column(String, primary_key = True)
2021-10-14 08:28:52 +03:00
title: str = Column(String, nullable=False, comment="Title")
body: str = Column(String, nullable=True, comment="Body")
pic: str = Column(String, nullable=True, comment="Picture")
children = Column(JSONType, nullable=True, default = [], comment="list of children topics")
2021-12-11 13:23:17 +03:00
community = Column(ForeignKey("community.slug"), nullable=False, comment="Community")
2021-12-12 16:00:38 +03:00
class TopicStorage:
topics = {}
lock = asyncio.Lock()
@staticmethod
def init(session):
self = TopicStorage
topics = session.query(Topic)
self.topics = dict([(topic.slug, topic) for topic in topics])
for topic in self.topics.values():
self.load_parents(topic)
@staticmethod
def load_parents(topic):
self = TopicStorage
parents = []
for parent in self.topics.values():
if topic.slug in parent.children:
parents.append(parent.slug)
topic.parents = parents
return topic
@staticmethod
async def get_topics(slugs):
self = TopicStorage
async with self.lock:
if not slugs:
return self.topics.values()
topics = filter(lambda topic: topic.slug in slugs, self.topics.values())
return list(topics)
@staticmethod
async def get_topics_by_community(community):
self = TopicStorage
async with self.lock:
topics = filter(lambda topic: topic.community == community, self.topics.values())
return list(topics)
@staticmethod
async def add_topic(topic):
self = TopicStorage
async with self.lock:
self.topics[topic.slug] = topic
self.load_parents(topic)