def update_stats(post, stats): """ Update stats by the new post. :param post: Post object :param stats: UserStats object :return: Updated UserStats """ stats.total_posts += 1 stats.total_post_rating += post.rating stats.total_post_word_count += post.word_count stats.total_post_character_count += post.character_count stats.average_post_word_count += safe_div(post.word_count - stats.average_post_word_count, stats.total_posts) stats.average_post_character_count += safe_div( post.character_count - stats.average_post_character_count, stats.total_post_word_count ) stats.average_post_rating += safe_div(post.rating - stats.average_post_rating, stats.total_post_rating) stats.save()
def process_reddit_post(cls, user, post, stats): """ Saves a reddit post in the database and update user's stats. :param user: :param post: :param stats: :return: User's UserStats """ name = post.name try: Post.objects.get(external_unique=name) return except Post.DoesNotExist: pass created = datetime.fromtimestamp(post.created_utc) try: raw_content = post.body except AttributeError: raw_content = post.selftext word_count = len(cls.WORDS_REGEX.findall(raw_content)) character_count = len(raw_content) upvote = post.ups downvote = post.downs rating = safe_div(upvote, upvote + downvote) post = Post.objects.create( user=user, oauth_client=REDDIT_OAUTHCLIENT, created=created, external_unique=name, raw_content=raw_content, word_count=word_count, character_count=character_count, upvote=upvote, downvote=downvote, rating=rating, ) cls.update_stats(post, stats)