Esempio n. 1
0
def get_comments(aid):
    '''``GET`` |API_URL_BASE|/article/:aid/comments/

    Get information of all comments to an article.

    :param limit: **Query** limit amount of comment per page,
        default: |COMMENT_LIST_DEFAULT_LIMIT|
    :param page: **Query**  page control, start from zero, default: 1

    Response JSON:

    .. code-block:: javascript

        // success
        {
            $errors: null,
            comments: [
                {
                    id: integer,
                    nickname: string,
                    content: string,
                    time: datetime,
                    reply_to: integer // maybe null if no references.
                }
            ]
        }

        // failed
        {$errors: {article_id: 'this article doesn't not exist.'}}

    Permission required: ``READ_COMMENT``
    '''
    default_limit = app_config['COMMENT_LIST_DEFAULT_LIMIT']

    try:
        author_id = (Article.select(Article.author)
                            .where(Article.id == aid).get()).author_id
    except Article.DoesNotExist:
        return {'article_id': '无法找到这篇文章,可能已经被删除'}

    page = request.args.get('page', 1, type=int) - 1
    limit = request.args.get('limit', default_limit, type=int)

    query = (Comment.select()
                    .where(Comment.article == aid)
                    .offset(page * limit).limit(limit + 1))

    if current_user.get_id() != author_id:
        query = query.where(Comment.reviewed == True)  # noqa: E712

    comments = [comment.to_dict() for comment in query]
    is_more = len(comments) > limit

    return None, {'is_more': is_more, 'comments': comments[:limit]}