Ejemplo n.º 1
0
def archive(year=None, month=None):
    posts = storage.get_posts_with_limits(include_draft=False)

    rel_url_prefix = ''
    archive_name = ''
    if year is not None:
        rel_url_prefix += '%04d/' % year
        archive_name += str(year)
    if month is not None:
        rel_url_prefix += '%02d/' % month
        archive_name += '.' + str(month)

    def convert_to_dict(post_):
        post_d = post_.to_dict()
        del post_d['raw_content']
        post_d['preview'], post_d['has_more_content'] = \
            get_parser(post_.format).parse_preview(post_.raw_content)
        post_d['url'] = make_abs_url(post_.unique_key)
        return post_d

    posts = list(
        map(convert_to_dict,
            filter(lambda p: p.rel_url.startswith(rel_url_prefix), posts)))
    return dict(entries=posts,
                archive_type='Archive',
                archive_name=archive_name if archive_name else 'All')
Ejemplo n.º 2
0
def test_get_posts_with_limits():
    with app.app_context():
        posts = storage.get_posts_with_limits(include_draft=True)
        assert posts == storage.get_posts(include_draft=True)

        posts = storage.get_posts_with_limits(include_draft=True, tags='Hello World', categories=['Default'])
        assert len(posts) == 2

        posts = storage.get_posts_with_limits(include_draft=True,
                                              created=(datetime.strptime('2016-02-02', '%Y-%m-%d'),
                                                       date(year=2016, month=3, day=3)))
        assert len(posts) == 1

        posts = storage.get_posts_with_limits(include_draft=True,
                                              created=(date(year=2011, month=2, day=2),
                                                       date(year=2014, month=2, day=2)))
        assert len(posts) == 0
Ejemplo n.º 3
0
def tag(tag_name):
    posts = storage.get_posts_with_limits(include_draft=False,
                                          **{'tags': [tag_name]})
    if not posts:
        abort(404)

    def convert_to_dict(post_):
        post_d = post_.to_dict()
        del post_d['raw_content']
        post_d['preview'], post_d['has_more_content'] = \
            get_parser(post_.format).parse_preview(post_.raw_content)
        post_d['url'] = make_abs_url(post_.unique_key)
        return post_d

    posts = list(map(convert_to_dict, posts))
    return dict(entries=posts, archive_type='Tag', archive_name=tag_name)
Ejemplo n.º 4
0
def posts(year: int = None, month: int = None, day: int = None,
          post_name: str = None):
    args = {k: [x.strip() for x in v.split(',')]
            for k, v in request.args.items()}

    for key in ('include_draft', 'start', 'count'):
        # pop out items that should not be passed into the 'get_posts' method
        # as 'limits'
        args.pop(key, None)

    # fields that the API user needs, a list or None
    fields = args.pop('fields', None)

    for key in ('created', 'updated'):
        if key in args:
            try:
                interval = args[key]
                # should be ['2017-02-13', '2017-03-13'] if it's valid
                for i in range(2):
                    y, m, d = re.match(
                        '(\d{4})-(\d{1,2})-(\d{1,2})', interval[i]).groups()
                    interval[i] = date(year=int(y), month=int(m), day=int(d))
            except (IndexError, AttributeError, ValueError):
                raise ApiException(
                    message='The "{}" argument is invalid, and it should be '
                            'like "2017-02-13,2017-03-13".'.format(key),
                    error=Error.INVALID_ARGUMENTS
                )

    # get the post list here
    result_posts = storage.get_posts_with_limits(include_draft=False, **args)

    return_single_item = False
    rel_url_prefix = ''
    if year is not None:
        rel_url_prefix += '%04d/' % year
    if month is not None:
        rel_url_prefix += '%02d/' % month
    if day is not None:
        rel_url_prefix += '%02d/' % day
    if post_name is not None:
        rel_url_prefix += '%s/' % post_name
        # if a full relative url is given, we return just ONE post,
        # instead of a list
        return_single_item = True
    result_posts = filter(lambda p: p.rel_url.startswith(rel_url_prefix),
                          result_posts)

    start = request.args.get('start', '')
    start = int(start) if start.isdigit() else 0
    count = request.args.get('count', '')
    count = int(count) if count.isdigit() else -1

    result_posts_list = []
    for post in islice(
            result_posts, start, start + count if count >= 0 else None):
        parser = get_parser(post.format)
        post_d = post.to_dict()
        del post_d['raw_content']
        if return_single_item:
            # if a certain ONE post is needed,
            # we parse all content instead of preview
            post_d['content'] = parser.parse_whole(post.raw_content)
            post_d['content'], post_d['toc'], post_d['toc_html'] = \
                parse_toc(post_d['content'])
        else:
            # a list of posts is needed, we parse only previews
            post_d['preview'], post_d['has_more_content'] = \
                parser.parse_preview(post.raw_content)
        if fields is not None:
            # select only needed fields to return
            assert isinstance(fields, list)
            full_post_d = post_d
            post_d = {}
            for key in fields:
                if key in full_post_d:
                    post_d[key] = full_post_d[key]
        result_posts_list.append(post_d)

    if result_posts_list and return_single_item:
        return result_posts_list[0]
    else:
        return result_posts_list if result_posts_list else None