python 34 lines · 6 steps

Paginating articles in a Flask Blueprint

A Flask route reads pagination params, validates them, and serves a page of published articles with SQLAlchemy.

Explained by highlit
1from flask import Blueprint, render_template, request, abort
2from sqlalchemy import select
3 
4from .models import Article
5from .extensions import db
6 
7bp = Blueprint("articles", __name__)
8 
9 
10@bp.route("/articles")
11def index():
12 page = request.args.get("page", 1, type=int)
13 per_page = request.args.get("per_page", 20, type=int)
14 if page < 1 or per_page < 1 or per_page > 100:
15 abort(400)
16 
17 query = (
18 select(Article)
19 .where(Article.published.is_(True))
20 .order_by(Article.published_at.desc())
21 )
22 
23 pagination = db.paginate(
24 query,
25 page=page,
26 per_page=per_page,
27 error_out=False,
28 )
29 
30 return render_template(
31 "articles/index.html",
32 articles=pagination.items,
33 pagination=pagination,
34 )
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Blueprints let you group related routes into a self-contained, mountable module.
  2. 2Validate and bound user-supplied pagination input before it ever reaches the database.
  3. 3Building the query separately from paginating it keeps filtering, ordering, and slicing cleanly composable.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Paginating articles in a Flask Blueprint — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code