Пример #1
0
def search():
    if not g.search_form.validate():
        return redirect(url_for('index'))
    page = request.args.get('page', 1, type=int)
    target_index = request.args.get('index', 'thread')
    if target_index == 'thread':
        results, total = Thread.search(g.search_form.q.data, page,
                                       app.config['POSTS_PER_PAGE'])
    elif target_index == 'user':
        results, total = User.search(g.search_form.q.data, page,
                                     app.config['POSTS_PER_PAGE'])
    elif target_index == 'subreddit':
        results, total = Subreddit.search(g.search_form.q.data, page,
                                          app.config['POSTS_PER_PAGE'])
    else:
        return render_template('404.html')

    results = results.all()
    next_url = url_for(
        'search', index=target_index, q=g.search_form.q.data, page=page +
        1) if total > page * app.config['POSTS_PER_PAGE'] else None
    prev_url = url_for(
        'search', index=target_index, q=g.search_form.q.data, page=page -
        1) if page > 1 else None
    return render_template('search.html',
                           title=_('Search'),
                           results=results,
                           next_url=next_url,
                           prev_url=prev_url,
                           query=g.search_form.q.data,
                           query_language=guess_language(g.search_form.q.data),
                           index=target_index)