search: Add pagination

This commit is contained in:
Eragon 2023-08-09 18:26:38 +02:00
parent 7e28531106
commit e52b3ebe41
Signed by: Eragon
GPG Key ID: 087126EBFC725006
2 changed files with 26 additions and 7 deletions

View File

@ -7,8 +7,22 @@ from app.models.forum import Forum
from app.utils.render import render
from sqlalchemy import text, func
from flask import request
from flask_sqlalchemy import Pagination
SEARCH_RESULTS_PER_PAGE = 20
def paginate(data, page, per_page):
# Based on page and per_page info, calculate start and end index of items to keep
start_index = (page - 1) * per_page
end_index = start_index + per_page
# Get the paginated list of items
items = data[start_index:end_index]
# Create Pagination object
return Pagination(None, page, per_page, len(data), items)
def websearch_to_tsquery_multilang(search):
return func.websearch_to_tsquery('french', search).op('||')(func.websearch_to_tsquery('english', search))
@ -16,26 +30,28 @@ def to_tsvector_multilang(text):
return func.to_tsvector('french', text).op('||')(func.to_tsvector('english', text))
@app.route('/rechercher')
def search():
@app.route('/rechercher/')
@app.route('/rechercher/<int:page>/')
def search(page=1):
form = AdvancedSearchForm(request.args)
results = list()
if form.validate():
# Topics are sorted first in results
tsquery = websearch_to_tsquery_multilang(form.q.data)
results = db.session.query(Topic).where(
topic_query = db.session.query(Topic).where(
to_tsvector_multilang(Topic.title).bool_op('@@')(tsquery)
).group_by(
Topic.id,
Post.id
)
# Comments are less important than topics and programs
res = db.session.query(Comment).where(
comments_query = db.session.query(Comment).where(
to_tsvector_multilang(Comment.text).bool_op('@@')(tsquery)
).group_by(
Comment.id,
Post.id
)
results = list(results) + list(res)
results = list(topic_query) + list(comments_query)
results = paginate(results, page, SEARCH_RESULTS_PER_PAGE)
return render('search.html', form=form, results=results)

View File

@ -1,4 +1,5 @@
{% extends "base/base.html" %}
{% import "widgets/pagination.html" as widget_pagination with context %}
{% set tabtitle = "Recherche avancée" %}
@ -6,7 +7,7 @@
<section class="form search">
<h1>Recherche avancée</h1>
<form action="" method="get">
<form action="{{ url_for('search') }}" method="get">
{{ form.csrf_token }}
<div class="query">
{{ form.q.label }}
@ -29,7 +30,8 @@
</form>
</section>
<section class="search-results">
{% for i in results %}
{{ widget_pagination.paginate(results, 'search', None, {'q': request.args.get('q')}) }}
{% for i in results.items %}
<div>
{{ i.id }} {{ i.title }} {{ i.forum }}<br>
{% if i.forum %}
@ -38,5 +40,6 @@
{{ i.headline }}<br>
</div>
{% endfor %}
{{ widget_pagination.paginate(results, 'search', None, {}) }}
</section>
{% endblock %}