Пример #1
0
 def post(self):
     data = request.get_json() or {}
     title = data.get("title")
     abstract = data.get("abstract")
     content = data.get("content")
     category = data.get("category")
     author = token_auth.current_user()
     if not title or not abstract or not content:
         return invalid_api_usage("No title, abstract or content provided",
                                  400)
     if Article.query.filter_by(title=title).first():
         return invalid_api_usage("Title is already exist", 400)
     item = Article(title,
                    abstract,
                    content,
                    category=category,
                    author=author.uid)
     item.author = author.uid
     db.session.add(item)
     db.session.commit()
     return {
         "title": item.title,
         "abstract": item.abstract,
         "content": item.content,
         "category": item.category,
         "slug": item.slug,
         "authorName":
         User.query.filter_by(uid=item.author).first().username,
         "created": item.created.isoformat(),
         "updated": item.updated.isoformat(),
     }, 201
Пример #2
0
def delete_article(article_id: str,
                   current_user: User = Depends(get_current_user)):
    article = Article.filter(Article.id == article_id, Article.user_id == current_user.uuid).first()
    if not article:
        return fail_response('此文章不存在')
    title = article.title
    try:
        # 之前这个是 物理删除
        # result = article.delete_instance()
        # 删除改为逻辑删除
        query = Article.update(is_delete=True).where(
            Article.id == article_id, Article.user_id == current_user.uuid)
        result = query.execute()
        # print(result, "运行后的结果")
        if result:
            res = redis_client.exists("article_rank_list")
            if res:
                # 存在了但是这个文章
                res_score = redis_client.zscore("article_rank_list", "article_%s_%s" % (article_id, title))
                if res_score:
                    # 删除之前的分数记录
                    redis_client.zrem("article_rank_list", "article_%s_%s" % (article_id, title))
            return success_response('删除博客文章成功')
        return fail_response('删除博客文章失败')
    except Exception as e:
        db.rollback()
        logger.error(f'删除博客文章失败,失败原因:{e}')
        return fail_response('删除博客文章失败')
Пример #3
0
def get_article_list(
        category_id: str = Path(0, description="博客分类id"),
        page: int = Query(1, description='页码'),
        page_size: int = Query(settings.PAGE_SIZE, description='每页条数'),
        search: str = Query(None, description='查询参数'),
        # start_time: datetime = Query(None, description='工单开始时间'),
        # end_time: datetime = Query(None, description='工单结束时间'),
):
    try:
        if category_id == '0':
            category_id = None
        if not search:
            articles = Article.select().where(Article.category_id == category_id).order_by(Article.create_time.desc())
        else:
            # 法二:
            articles = Article.select().where(
                Article.category_id == category_id,
                Article.title.contains(search) |
                Article.desc.contains(search) |
                Article.content.contains(search)).order_by(Article.create_time.desc())
        # # 参数校验
        # if (not start_time or not end_time) and (start_time or end_time):
        #     return fail_response('时间错误')
        # if start_time and end_time:
        #     if start_time > end_time or (end_time - datetime.now()).total_seconds() > 24 * 60 * 60:
        #         return fail_response('时间错误')
        # if start_time and end_time:
        #     articles = articles.where(Article.create_time >= start_time, Article.create_time <= end_time)
        paginate_articles = articles.paginate(page, page_size)
        paginate = {
            'page': page,
            'page_size': page_size,
            'total': articles.count()
        }
        if not paginate_articles:
            return success_response({
                'paginate': paginate,
                'product_list': []
            })
        article_list = [article.to_dict() for article in paginate_articles]
        data = {
            'paginate': paginate,
            'article_list': article_list
        }
        return success_response(data)
    except Exception as e:
        logger.error(f'获取文章列表失败,失败原因:{e}')
        return fail_response('获取文章列表失败')
Пример #4
0
def get_article_info(article_id: str):
    """
    在排行榜这款  需要把 标题也存进去
    :param article_id:
    :return:
    """
    article = Article.filter(Article.is_delete == 0, Article.id == article_id).first()
    if article:
        title = article.title
        res = redis_client.exists("article_rank_list")
        if not res:
            # 连有序集合都没有的情况 初始化分数
            redis_client.zadd("article_rank_list", {"article_%s_%s" % (article_id, title): 1})
            # print(redis_client.zscore("article_rank_list", "article_id_1"))
        else:
            # 存在了但是这个文章
            res_score = redis_client.zscore("article_rank_list", "article_%s_%s" % (article_id, title))
            if res_score is None:
                # 初始化分数
                redis_client.zadd("article_rank_list", {"article_%s_%s" % (article_id, title): 1})
            # 存在这个key的时候就分值增加 1
            redis_client.zincrby("article_rank_list", 1, "article_%s_%s" % (article_id, title))
        page_view = redis_client.zscore("article_rank_list", "article_%s_%s" % (article_id, title))
        # return success_response(score)
        # redis_client.incr('article_id:%s' % article_id)
        # page_view = redis_client.get('article_id:%s' % article_id)
        data = {"title": article.title,
                "desc": article.desc,
                "content": article.content,
                "create_time": str(article.create_time),
                "update_time": str(article.update_time),
                "page_view": page_view}

        return success_response(data)
    return fail_response("文章不存在")
Пример #5
0
def reply_comment(create_comment: CreateComment,
                  article_id: str = Path(2, description="博客文章id"),
                  comment_id: str = Path(2, description="评论id"),
                  current_user: User = Depends(get_current_user)):
    content = create_comment.content
    article = Article.filter(Article.id == article_id).first()
    if not article:
        return fail_response('此文章不存在')
    if article.user_id == current_user.uuid:
        # 博主的情况
        comment = Comment.filter(Comment.id == comment_id, Comment.article_id == article_id,
                                 Comment.user_id != current_user.uuid).first()
    else:
        # 用户
        comment = Comment.filter(Comment.id == comment_id, Comment.article_id == article_id,
                                 Comment.user_id != current_user.uuid,
                                 Comment.parent_id != '').first()
    if not comment:
        return fail_response('此评论不存在或原评论你不能进行回复!')
    try:
        Comment.create(article_id=article_id, user_id=current_user.uuid, content=content, parent_id=comment.id)
    except Exception as e:
        db.rollback()
        logger.error(f'评论回复失败,失败原因:{e}')
        return fail_response('评论回复失败')
    return success_response('评论回复成功!')
Пример #6
0
def get_comment_list(article_id: str):
    article = Article.filter(Article.id == article_id).first()
    if not article:
        return fail_response('此文章不存在')
    comment_query = Comment.select().order_by(Comment.create_time.desc())
    count = comment_query.count()
    comment_list = [comment.to_dict() for comment in comment_query]
    return success_response({"count": count,
                             "comment_list": comment_list})
Пример #7
0
def create_article(app: Flask) -> Article:
    with app.app_context():
        admin = User.query.filter_by(username="******").first()
        article = Article("test title",
                          "test abstract",
                          "test content",
                          author=admin.uid)
        db.session.add(article)
        db.session.commit()
        article = Article.query.filter_by(title="test title").first()
    return article
Пример #8
0
def create_articles(app: Flask) -> None:
    print("create some fake articles")
    with app.app_context():
        for _ in range(100):
            article = Article(title(),
                              abstract(),
                              content(),
                              author=get_admin(app).uid,
                              category=get_random_category(app).slug)
            db.session.add(article)
            db.session.commit()
Пример #9
0
def update_article(article_id: str,
                   new_article: UpdateArticle,
                   current_user: User = Depends(get_current_user)):
    title = new_article.title
    desc = new_article.desc
    content = new_article.content
    category_id = new_article.category_id
    article = Article.filter(Article.id == article_id, Article.user_id == current_user.uuid,
                             Article.is_delete == 0).first()
    if not article:
        return fail_response('此文章不存在')
    try:
        query = Article.update(title=title, desc=desc, content=content, category_id=category_id,
                               update_time=str(datetime.now)).where(
            Article.id == article_id, Article.user_id == current_user.uuid)
        query.execute()
        # 修改排行榜的标题
        res = redis_client.exists("article_rank_list")
        if not res:
            # 连有序集合都没有的情况 初始化分数 0
            redis_client.zadd("article_rank_list", {"article_%s_%s" % (article_id, title): 0})
            # print(redis_client.zscore("article_rank_list", "article_id_1"))
        else:
            # 存在了但是这个文章
            res_score = redis_client.zscore("article_rank_list", "article_%s_%s" % (article_id, title))
            if res_score is None:
                # 初始化分数
                redis_client.zadd("article_rank_list", {"article_%s_%s" % (article_id, title): 0})
            else:
                # 删除之前的分数记录
                redis_client.zrem("article_rank_list", "article_%s_%s" % (article_id, title))

                # 重新建立一个并将之前的分数给这个
                redis_client.zadd("article_rank_list", {"article_%s_%s" % (article_id, title): res_score})
            # 存在这个key的时候就分值增加 1
            redis_client.zincrby("article_rank_list", 1, "article_%s_%s" % (article_id, title))
        return success_response('更新博客文章成功')
    except Exception as e:
        db.rollback()
        logger.error(f'更新博客文章失败,失败原因:{e}')
        return fail_response('更新博客文章失败')
Пример #10
0
def get_article_info(article_id: str):
    article = Article.filter(Article.id == article_id).first()
    if not article:
        return fail_response('此文章不存在')
    try:
        up_count = ArticleUpDown.filter(ArticleUpDown.article_id == article.id, ArticleUpDown.is_up == True).count()
    except Exception as e:
        db.rollback()
        logger.error(f'更新博客文章失败,失败原因:{e}')
        return fail_response('删除博客文章失败')
    return success_response({"article_id": article_id,
                             "up_count": up_count})
Пример #11
0
def create_article(*, new_article: CreateArticle,
                   current_user: User = Depends(get_current_user)):
    title = new_article.title
    desc = new_article.desc
    content = new_article.content
    category_id = new_article.category_id
    article = Article.filter(Article.user_id == current_user.uuid).first()
    if article:
        fail_response("您的博客文章已创建,不能重复创建")
    try:
        new_article = Article.create(title=title,
                                     desc=desc,
                                     content=content,
                                     user_id=current_user.uuid,
                                     category_id=category_id)
        print(new_article.title)
    except Exception as e:
        db.rollback()
        logger.error(f'创建博客文章失败,失败原因:{e}')
        return fail_response('创建博客文章失败')
    return success_response('创建博客文章成功')
Пример #12
0
def create_articles(app: Flask) -> None:
    article_titles = ["test title " + str(i) for i in range(10)]
    category = create_category(app)
    with app.app_context():
        for title in article_titles:
            admin = User.query.filter_by(username="******").first()
            article = Article(title,
                              "test abstarct",
                              "test content",
                              author=admin.uid,
                              category=category.slug)
            db.session.add(article)
            db.session.commit()
Пример #13
0
def add_comment(create_comment: CreateComment,
                article_id: str = Path(2, description="博客文章id"),
                current_user: User = Depends(get_current_user)):
    content = create_comment.content
    article = Article.filter(Article.id == article_id).first()
    if not article:
        return fail_response('此文章不存在')
    try:
        Comment.create(article_id=article_id, user_id=current_user.uuid, content=content, parent_id=None)
    except Exception as e:
        db.rollback()
        logger.error(f'博客文章评论失败,失败原因:{e}')
        return fail_response('删除博客文章失败')
    return success_response('新增评论成功!')
Пример #14
0
def get_article_up_count(article_id: str,
                         current_user: User = Depends(get_current_user)):
    article = Article.filter(Article.id == article_id, Article.user_id == current_user).first()
    if not article:
        return fail_response('此文章不存在')
    try:
        article_likes = ArticleUpDown.filter(ArticleUpDown.article_id == article.id, ArticleUpDown.is_up == True)
        user_list = [article_like.user_id.username for article_like in article_likes]
        up_count = article_likes.count()
    except Exception as e:
        db.rollback()
        logger.error(f'更新博客文章失败,失败原因:{e}')
        return fail_response('删除博客文章失败')
    return success_response({"user_list": user_list,
                             "up_count": up_count})
Пример #15
0
def article_down(article_id: str,
                 up_down: UpDown,
                 current_user: User = Depends(get_current_user)):
    is_up = up_down.is_up
    article = Article.filter(Article.id == article_id).first()
    if not article:
        return fail_response('此文章不存在')
    article_like = ArticleUpDown.filter(ArticleUpDown.user_id == current_user.uuid,
                                        ArticleUpDown.article_id == article_id).first()
    if article_like and article_like.is_up == is_up:
        pass
    elif article_like and article_like.is_up != is_up:
        article_like.is_up = is_up
        article_like.save()
    else:
        return fail_response('点赞操作失败')
    return success_response('点赞操作成功')
Пример #16
0
def delete_comment(article_id: str,
                   comment_id: str,
                   current_user: User = Depends(get_current_user)):
    article = Article.filter(Article.id == article_id).first()
    if not article:
        return fail_response('此文章不存在')
    comment = Comment.filter(Comment.article_id == article_id, Comment.id == comment_id,
                             Comment.user_id == current_user.uuid).first()
    if not comment:
        return fail_response('此评论不存在或你没有删除权限')
    try:
        result = comment.delete_instance()
        if not result:
            return fail_response('删除评论失败')
    except Exception as e:
        db.rollback()
        logger.error(f'删除评论失败失败,失败原因:{e}')
        return fail_response('删除评论失败!')
    return success_response('删除评论成功!')
Пример #17
0
def update_comment(article_id: str,
                   comment_id: str,
                   create_comment: CreateComment,
                   current_user: User = Depends(get_current_user)):
    content = create_comment.content
    article = Article.filter(Article.id == article_id).first()
    if not article:
        return fail_response('此文章不存在')
    comment = Comment.filter(Comment.article_id == article_id, Comment.id == comment_id,
                             Comment.user_id == current_user.uuid).first()
    if not comment:
        return fail_response('此评论不存在')
    try:
        comment.content = content
        comment.save()
    except Exception as e:
        db.rollback()
        logger.error(f'博客文章评论修改失败,失败原因:{e}')
        return fail_response('博客文章评论修改失败!')
    return success_response('博客文章评论修改成功!')
Пример #18
0
def get_article_list(
        page: int = Query(1, description='页码'),
        page_size: int = Query(settings.PAGE_SIZE, description='每页条数'),
        article_id: int = Query(None, description='文章ID'),
        title: str = Query(None, description='文章标题'),
        desc: str = Query(None, description='文章描述'),
        content: str = Query(None, description='文章内容'),
):
    try:
        article_query = Article.select()
        if article_id:
            article_query = article_query.where(Article.id.contains(article_id))
        if title:
            article_query = article_query.where(Article.title.contains(title))
        if desc:
            article_query = article_query.where(Article.desc.contains(desc))
        if content:
            article_query = article_query.where(Article.content.contains(content))
        # paginate_articles = article_query.limit(page_size).offset((page-1)*page_size) # 得到的结果同下
        paginate_articles = article_query.paginate(page, page_size)
        paginate = {
            'page': page,
            'page_size': page_size,
            'total': article_query.count()
        }
        if not paginate_articles:
            return success_response({
                'paginate': paginate,
                'product_list': []
            })
        article_list = [article.to_dict() for article in paginate_articles]
        data = {
            'paginate': paginate,
            'article_list': article_list
        }

        return success_response(data)
    except Exception as e:
        logger.error(f'获取文章列表失败,失败原因:{e}')
        return fail_response('获取文章列表失败')
Пример #19
0
def article_up(article_id: str,
               up_down: UpDown,
               current_user: User = Depends(get_current_user)):
    is_up = up_down.is_up
    article = Article.filter(Article.id == article_id).first()
    if not article:
        return fail_response('此文章不存在')
    article_like = ArticleUpDown.filter(ArticleUpDown.user_id == current_user.uuid,
                                        ArticleUpDown.article_id == article_id).first()
    if article_like and article_like.is_up == is_up:
        pass
    elif article_like and article_like.is_up != is_up:
        article_like.is_up = is_up
        article_like.save()
    else:
        try:
            ArticleUpDown.create(user_id=current_user, article_id=article, is_up=is_up)
        except Exception as e:
            db.rollback()
            logger.error(f'点赞操作失败,失败原因:{e}')
            return fail_response('点赞操作失败')
    return success_response('操作成功成功')
Пример #20
0
def delete_category(category_id: str, current_user: User = Depends(get_current_user)):
    # 法一:
    # blog_site = BlogSite.filter(BlogSite.user_id == current_user.uuid).first()
    # if blog_site is None:
    #     return fail_response('此用户未创建博客站点,请先创建')
    # category = Category.filter(Category.id == category_id, Category.blog_id == blog_site.id).first()
    # if not category:
    #     return fail_response("博客分类不存在")
    # try:
    #     result = category.delete_instance()
    #     if result:
    #         return success_response('删除博客文章成功')
    #     return fail_response('更新博客文章失败')
    # except Exception as e:
    #     db.rollback()
    #     logger.error(f'更新博客文章失败,失败原因:{e}')
    #     return fail_response('删除博客文章失败')
    # 法二:使用联表查询的方式
    category = Category.select().join(BlogSite, on=(Category.blog_id == BlogSite.id)).where(
        BlogSite.user_id == current_user.uuid, Category.id == category_id)
    if not category:
        return fail_response("博客分类不存在")
    try:
        # 先将这个用户下这个分类的文章的分类改为空值
        articles = Article.filter(Article.category_id == category_id)
        for article in articles:
            article.category_id = None
            article.save()
        # 再将这个文章分类删掉
        query = Category.delete().where(Category.id == category_id)
        result = query.execute()  # 删除成功返回 1  所以不等于1为失败
        if result != 1:
            return fail_response('更新博客文章失败')
    except Exception as e:
        db.rollback()
        logger.error(f'更新博客文章失败,失败原因:{e}')
        return fail_response('删除博客文章失败')
    return success_response('删除博客文章成功')
Пример #21
0
def get_article_list(
        page: int = Query(1, description='页码'),
        page_size: int = Query(settings.PAGE_SIZE, description='每页条数'),
        search: str = Query(None, description='查询参数'),
        start_time: datetime = Query(None, description='工单开始时间'),
        end_time: datetime = Query(None, description='工单结束时间'),
):
    try:
        if not search:
            articles = Article.select().order_by(Article.create_time.desc())
        else:
            # 法一:
            # articles = Article.select().where(
            #     Article.title % f'%{search}%' |
            #     Article.desc % f'%{search}%' |
            #     Article.content % f'%{search}%').order_by(Article.create_time.desc())
            # 法二:
            articles = Article.select().where(
                Article.title.contains(search) |
                Article.desc.contains(search) |
                Article.content.contains(search)).order_by(Article.create_time.desc())
        # 参数校验
        if (not start_time or not end_time) and (start_time or end_time):
            return fail_response('时间错误')
        if start_time and end_time:
            if start_time > end_time or (end_time - datetime.now()).total_seconds() > 24 * 60 * 60:
                return fail_response('时间错误')
        if start_time and end_time:
            articles = articles.where(Article.create_time >= start_time, Article.create_time <= end_time)
        paginate_articles = articles.paginate(page, page_size)
        paginate = {
            'page': page,
            'page_size': page_size,
            'total': articles.count()
        }
        if not paginate_articles:
            return success_response({
                'paginate': paginate,
                'product_list': []
            })
        # 法一:
        # article_list = []
        # for article in paginate_articles:
        #     article_list.append({
        #         'id': article.id,
        #         'title': article.title,
        #         'desc': article.desc,
        #         'content': article.content,
        #         'create_time': str(article.create_time),
        #         'update_time': str(article.update_time)
        #     })
        # 法二:(相应的模型需要加to_dict的方法)
        # for article in paginate_articles:
        #     article_list.append(article.to_dict())
        # 法三:使用列表推导式
        article_list = [article.to_dict() for article in paginate_articles]
        data = {
            'paginate': paginate,
            'article_list': article_list
        }

        return success_response(data)
    except Exception as e:
        logger.error(f'获取文章列表失败,失败原因:{e}')
        return fail_response('获取文章列表失败')