From e52b3ebe411c653b2e57f3ed65fdc3ab063c2bb3 Mon Sep 17 00:00:00 2001 From: Eragon Date: Wed, 9 Aug 2023 18:26:38 +0200 Subject: [PATCH] search: Add pagination --- app/routes/search.py | 26 +++++++++++++++++++++----- app/templates/search.html | 7 +++++-- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/app/routes/search.py b/app/routes/search.py index aa56141..06611cf 100644 --- a/app/routes/search.py +++ b/app/routes/search.py @@ -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//') +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) diff --git a/app/templates/search.html b/app/templates/search.html index 2f792e2..25ab122 100644 --- a/app/templates/search.html +++ b/app/templates/search.html @@ -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 @@
- {% for i in results %} + {{ widget_pagination.paginate(results, 'search', None, {'q': request.args.get('q')}) }} + {% for i in results.items %}
{{ i.id }} {{ i.title }} {{ i.forum }}
{% if i.forum %} @@ -38,5 +40,6 @@ {{ i.headline }}
{% endfor %} + {{ widget_pagination.paginate(results, 'search', None, {}) }}
{% endblock %}