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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Blueprints let you group related routes into a self-contained, mountable module.
- 2Validate and bound user-supplied pagination input before it ever reaches the database.
- 3Building the query separately from paginating it keeps filtering, ordering, and slicing cleanly composable.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/paginating-articles-in-a-flask-blueprint-explained-python-b738/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.