Example #1
0
def add_comments():
    """
    Create db entries for comments
    :return:
    """
    comments = get_articles_comments(get_hot_article_ids(), get_ids=True)
    for index, comment in enumerate(comments):
        logger.info("[VIEW COMMENT {}]".format(index))
        comment_id, comment_text = comment
        print("[VIEW] Comment {}".format(index))

        comment_obj, created = Comment.add(comment_id, comment_text)
        if not created and comment_obj.text == comment_text:
            continue
        counted_words = get_words_count(comment_text)

        # delete old words
        if not created:
            words_to_delete = (
                db.session.query(WordsCount)
                .filter(
                    WordsCount.comment == comment_obj,
                    ~WordsCount.word.has(Word.text.in_([s[0] for s in counted_words])),
                )
                .all()
            )
            if words_to_delete:
                for word in words_to_delete:
                    db.session.delete(word)

        for word, count in counted_words:
            word_obj, created = Word.add(word)
            WordsCount.add(comment_obj, word_obj, count)

        db.session.commit()

    return render_template("stats.html", data=comments)