def collect_posts(post_types, before_ts, per_page, tag, search=None,
                  include_hidden=False):
    query = Post.query
    query = query.options(
        sqlalchemy.orm.subqueryload(Post.tags),
        sqlalchemy.orm.subqueryload(Post.mentions),
        sqlalchemy.orm.subqueryload(Post.reply_contexts),
        sqlalchemy.orm.subqueryload(Post.repost_contexts),
        sqlalchemy.orm.subqueryload(Post.like_contexts),
        sqlalchemy.orm.subqueryload(Post.bookmark_contexts))
    if tag:
        query = query.filter(Post.tags.any(Tag.name == tag))
    if not include_hidden:
        query = query.filter_by(hidden=False)
    query = query.filter_by(deleted=False, draft=False)
    if post_types:
        query = query.filter(Post.post_type.in_(post_types))
    if search:
        query = query.filter(
            sqlalchemy.func.concat(Post.title, ' ', Post.content)
            .op('@@')(sqlalchemy.func.plainto_tsquery(search)))

    try:
        if before_ts:
            before_dt = datetime.datetime.strptime(before_ts, BEFORE_TS_FORMAT)
            before_dt = TIMEZONE.normalize(TIMEZONE.localize(before_dt))
            before_dt = before_dt.astimezone(pytz.utc)
            before_dt = before_dt.replace(tzinfo=None)

            query = query.filter(Post.published < before_dt)
    except __HOLE__:
        current_app.logger.warn('Could not parse before timestamp: %s',
                                before_ts)

    query = query.order_by(Post.published.desc())
    query = query.limit(per_page)
    posts = query.all()

    posts = [post for post in posts if check_audience(post)]
    if posts:
        last_ts = posts[-1].published
        last_ts = pytz.utc.localize(last_ts)
        last_ts = TIMEZONE.normalize(last_ts.astimezone(TIMEZONE))\
                          .replace(tzinfo=None)

        view_args = request.view_args.copy()
        view_args['before_ts'] = last_ts.strftime(BEFORE_TS_FORMAT)
        for k, v in request.args.items():
            view_args[k] = v
        older = url_for(request.endpoint, **view_args)
    else:
        older = None

    return posts, older
dataset/ETHPy150Open kylewm/redwind/redwind/views.py/collect_posts