class Thread(Base): json_attributes = ("id", "title", "slug", "content", "user_id", "category_id", "comments_count") __tablename__ = "threads" title = db.Column(db.String(100), nullable=False) slug = db.Column(db.String(250), nullable=False) content = db.Column(db.Text) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) category_id = db.Column(db.Integer, db.ForeignKey("categories.id")) views_count = db.Column(db.Integer, nullable=False, default=0) comments_count = db.Column(db.Integer, default=0) best_comment_id = db.Column(db.Integer, nullable=True) owner = db.relationship("User", back_populates="threads") category = db.relationship("Category", back_populates="threads") comments = db.relationship("Comment", back_populates="thread") @property def summary(self): return self.content[0:300] + "..." def is_owner(self, user): return user == self.owner def add_comment(self, content, owner): comment = Comment(content=content, user_id=owner.id, thread_id=self.id) comment.save() return comment @hybrid_property def has_comments(self): return self.comments_count > 0
class Text(Thread): __tablename__ = 'texts' text = db.Column(db.Text, nullable=False) upvoters = db.relationship('ThreadUpvote', backref='text', lazy='dynamic') downvoters = db.relationship('ThreadDownvote', backref='text', lazy='dynamic') comments = db.relationship('Comment', backref='text', lazy='dynamic') def __repr__(self): return f'<Text: {self.title}>' def get_score(self): return self.upvote - self.downvote def get_time(self): now = datetime.datetime.now() return timeago.format(now, self.modified_on) @classmethod def is_link(self): return False def save(self): super().save() ThreadUpvote(user_id=self.user_id, text_id=self.id).save()
class User(Base, UserMixin): __tablename__ = "users" name = db.Column(db.String(255)) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) avatar = db.Column(db.String(150), default="avatar.png") email_verified_at = db.Column(db.DateTime, nullable=True, default=None) confirmation_token = db.Column(db.String(200), nullable=True, default=None) threads = db.relationship("Thread", back_populates="owner") comments = db.relationship("Comment", back_populates="owner") @classmethod def create(cls, **kwargs): user = cls(**kwargs) user.save() return user def json_attributes(self): return { "id": self.id, "email": self.email, "name": self.name, "profilePicture": self.profile_picture, "email_verified": self.email_verified_at is not None } @property def profile_picture(self): return url_for("static", filename="images/avatars/" + self.avatar)
class User(db.Model, UserMixin): __tablename__ = 'users' uid = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20)) _password = db.Column(db.String(20)) _email = db.Column(db.String(20), unique=True) posts = db.relationship("Post", backref="user") comments = db.relationship("Comment", backref="user") likes = db.relationship("Like", backref="user") def __init__(self, username, _password, _email): self.username = username self._password = _password self._email = _email @classmethod def all_users(self): return self.query.all() @classmethod def getUserById(self, uid): return self.query.get(uid) @classmethod def getEmail(self): return self._email def get_id(self): try: return text_type(self.uid) except AttributeError: raise NotImplementedError('No `id` attribute - override `get_id`')
class Comment(Base): __tablename__ = "comments" content = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) thread_id = db.Column(db.Integer, db.ForeignKey("threads.id")) owner = db.relationship("User", back_populates="comments") thread = db.relationship("Thread", back_populates="comments") def is_owner(self, user): print(self.user_id, user.id) return self.owner == user
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(50), unique=True, nullable=False) password = db.Column(db.String(60), nullable=False) profile_picture = db.Column(db.String(100), nullable=True, default='default.jpg') date_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) posts = db.relationship('Post', backref='author', lazy=True) activities = db.relationship('Activity', backref='author', lazy=True) def __repr__(self): return f"User('{self.id}',{self.email}'.'{self.profile_picture}')"
class Tag(db.Model): id = db.Column(db.Integer, primary_key=True) text = db.Column(db.String(32), nullable=False) message_id = db.Column(db.Integer, db.ForeignKey( 'message.id'), nullable=False) message = db.relationship('Message', backref=db.backref('tags', lazy=True))
class Topic(db.Model): __tablename__ = 'topics' tid = db.Column(db.Integer, primary_key=True) topic = db.Column(db.String(20)) _description = db.Column(db.String(20)) parent_id = db.Column(db.String(20)) posts = db.relationship("Post", backref="topics") path = None def __init__(self, topic, _description, parent_id): self.topic = topic self._description = _description self.parent_id = parent_id @classmethod def all_topics(self): return self.query.all() @classmethod def getTopicById(self, tid): return self.query.get(tid) @classmethod def getTopicList(self): return [{t.topic} for t in Topic.all_topics()]
class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False, unique=True) email = db.Column(db.String(255), nullable=False) password = db.Column(db.String(255), nullable=False) image_file = db.Column(db.String(20), nullable=False, default='default.jpg') registered_on = db.Column(db.DateTime, nullable=False, default=db.func.current_timestamp()) texts = db.relationship('Text', backref='user', lazy='dynamic') links = db.relationship('Link', backref='user', lazy='dynamic') comments = db.relationship('Comment', backref='user', lazy='dynamic') post_karma = db.Column(db.Integer, nullable=False, default=0) comment_karma = db.Column(db.Integer, nullable=False, default=0) has_upvoted = db.relationship('ThreadUpvote', backref='user', lazy='dynamic') has_downvoted = db.relationship('ThreadDownvote', backref='user', lazy='dynamic') has_upvoted_comment = db.relationship('CommentUpvote', backref='user', lazy='dynamic') has_downvoted_comment = db.relationship('CommentDownvote', backref='user', lazy='dynamic')
class Post(db.Model): __tablename__ = 'posts' pid = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) post_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow()) uid = db.Column(db.Integer, db.ForeignKey('users.uid'), nullable=False) tid = db.Column(db.Integer, db.ForeignKey('topics.tid'), nullable=False) comments = db.relationship("Comment", backref="posts") likes = db.relationship("Like", backref="posts") def __init__(self, title, content, post_time, uid, tid): self.title = title self.content = content self.post_time = post_time self.uid = uid self.tid = tid
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), nullable=False, unique=True) email = db.Column(db.String(120), nullable=False, unique=True) password = db.Column(db.String(60), nullable=False) type = db.Column(db.Integer, nullable=False) posts = db.relationship('Post', backref='author', lazy=True) def __repr__(self): return f"User({self.username}, {self.email})"
class Message(db.Model): __tablename__ = "messages" id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid4) text = db.Column(db.Text()) category_id = db.Column(UUID(as_uuid=True), db.ForeignKey("categories.id")) author_id = db.Column(UUID(as_uuid=True), db.ForeignKey("users.id")) posted_at = db.Column(db.DateTime) category = db.relationship("Category", backref=db.backref("messages", lazy=True)) user = db.relationship("User", backref=db.backref("messages", lazy=True)) def __repl__(self): return "<Message author='%s' posted_at='%s'>" % (self.author_id, self.posted_at) def __str__(self): return self.__repl__()
class Category(Base): __tablename__ = "categories" name = db.Column(db.String(100)) slug = db.Column(db.String(200)) threads = db.relationship("Thread", back_populates="category") def to_json(self): return {"id": self.id, "name": self.name, "slug": self.slug}
class Comment(db.Model): __tablename__ = 'comments' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) content = db.Column(db.Text, nullable=False) upvote = db.Column(db.Integer, nullable=False, default=0) upvoters = db.relationship('CommentUpvote', backref='comment', lazy='dynamic') downvoters = db.relationship('CommentDownvote', backref='comment', lazy='dynamic') downvote = db.Column(db.Integer, nullable=False, default=0) modified_on = db.Column( db.DateTime, default=datetime.datetime.now(), onupdate=datetime.datetime.now(), ) link_id = db.Column(db.Integer, db.ForeignKey('links.id'), nullable=True) text_id = db.Column(db.Integer, db.ForeignKey('texts.id'), nullable=True) comment_id = db.Column(db.Integer, db.ForeignKey('comments.id'), nullable=True) children = db.relationship('Comment', backref=db.backref('parent', remote_side=[id]), lazy='dynamic') def __repr__(self): return f"{self.content} | {self.id}" def get_score(self): """Get score of a comment""" return self.upvote - self.downvote def save(self): db.session.add(self) db.session.commit() CommentUpvote(user_id=self.user_id, comment_id=self.id).save()
class Subreddit(db.Model): __tablename__ = 'subreddits' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False, unique=True) subscribers = db.Column(db.Integer, default=0) description = db.Column(db.String(1000), unique=False) created_on = db.Column(db.DateTime, nullable=False, default=db.func.current_timestamp()) texts = db.relationship('Text', backref='subreddit', lazy='dynamic') links = db.relationship('Link', backref='subreddit', lazy='dynamic') def __repr__(self): return f"<Subreddit: {self.name} | " + \ f"Description: {self.description[:50]}>" def save(self): db.session.add(self) db.session.commit()
class Post(db.Model): post_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) body = db.Column(db.String(250), nullable=False) image = db.Column(db.String(100), nullable=True, default='default.jpg') id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) date_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) activities = db.relationship('Activity', backref='post', lazy=True) def __repr__(self): return f"Post('{self.post_id}','{self.title}','{self.body}','{self.image}','{self.id}')"
class Category(db.Model): __tablename__ = "categories" id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid4) name = db.Column(db.String(), nullable=False) parent_id = db.Column(UUID(as_uuid=True), db.ForeignKey("categories.id")) parent = db.relationship("Category", remote_side=[id]) def __repl__(self): return "<Category id='%s' name='%s'>" % (self.id, self.name) def __str__(self): return self.__repl__()
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key = True) username = db.Column(db.String(20), unique = True, nullable = False) password = db.Column(db.String(60), nullable = False) topics = db.relationship("Topic", backref = "author", lazy = True)
class Post(db.Model): """Model for the Post object. Attributes ---------- id : int The automatically-generated database id of the post title : string The title of the post body : string The body of the post. HTML is allowed for rich text, but script tags are not to prevent XSS attacks author_id : int The database ID of the user that created the post author : User The user object associated with the author_id. This is automatically created as a back-reference by SQLAlchemy on insertion and not declared explicitly amongst the class attributes creation_date : datetime The date the Post instance was created last_updated : datetime The date the Post instance was last updated views : int The number of times the Post was viewed liked_by : list List of user accounts that liked this post Methods ------- to_json() Returns the post's fields in a JSON serializable format """ id = db.Column(db.Integer, primary_key=True) title = db.Column(db.Text, nullable=False) body = db.Column(db.Text, nullable=False) author_id = db.Column( db.Integer, db.ForeignKey('user.id') ) creation_date = db.Column(db.DateTime, default=datetime.datetime.utcnow) last_updated = db.Column(db.DateTime, default=datetime.datetime.utcnow) views = db.Column(db.Integer, default=0) liked_by = db.relationship('User', secondary=posts, lazy='subquery', backref=db.backref('liked', lazy=True)) comments = db.relationship('Comment', backref='post', lazy=True) def to_json(self) -> dict: """Returns the post's fields in a JSON serializable format. Returns ------- dict The post's ID as integer, title as string, body as string, author as string of just username, creation_date as formatted datetime string, last_updated as formatted datetime string, views as integer, and liked_by as list of usernames """ author = self.author.username if self.author else 'undefined' return { 'id': self.id, 'title': self.title, 'body': self.body, 'author': author, 'creation_date': self.creation_date.strftime(TIME_FMT), 'last_updated': self.last_updated.strftime(TIME_FMT), 'views': self.views, 'liked_by': [user.username for user in self.liked_by], 'comments': [comment.to_json() for comment in self.comments] }
class User(db.Model): """Model for the User object. Attributes ---------- id : int The automatically-generated database id of the user username : string The chosen visible name of the user account password : string The hashed password for the user of the account creation_date : datetime The date the user instance was created last_updated : datetime The date the user instance was last modified bio : string The user's own description of themselves posts : list The list of posts this user has created Methods ------- to_json() Returns the user's fields in a JSON serializable format """ id = db.Column(db.Integer, primary_key=True) username = db.Column(db.Unicode, nullable=False) password = db.Column(db.Unicode, nullable=False) creation_date = db.Column(db.DateTime, default=datetime.datetime.utcnow) last_updated = db.Column(db.DateTime, default=datetime.datetime.utcnow) bio = db.Column(db.Text) token = db.Column(db.Unicode) posts = db.relationship('Post', backref='author', lazy=True) comments = db.relationship('Comment', backref='author', lazy=True) def __init__(self, *args, **kwargs) -> None: """Overrides the inherited init method to hash incoming passwords.""" kwargs["password"] = hasher.hash(kwargs["password"]) kwargs["token"] = secrets.token_urlsafe(64) super().__init__(*args, **kwargs) def to_json(self) -> dict: """Returns the user's fields in a JSON serializable format. Returns ------- dict The user's ID as integer, username as string, creation_date and last_updated as formatted datetime string, and bio as string. """ return { 'id': self.id, 'username': self.username, 'creation_date': self.creation_date.strftime(TIME_FMT), 'last_updated': self.last_updated.strftime(TIME_FMT), 'bio': self.bio, 'posts': [post.to_json() for post in self.posts] }