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
import argparse import sys from pathlib import Path
Building a subcommand CLI with argparse
cli
argparse
subcommands
Intermediate
6 steps
python
from collections.abc import Mapping from typing import Any, Iterator
Flattening nested config into dotted keys
recursion
generators
tree-traversal
Intermediate
7 steps
javascript
const express = require('express'); const v1 = express.Router();
Versioning an API with Express Routers
api versioning
routing
modularity
Intermediate
10 steps
python
import csv import io from datetime import datetime
Streaming a CSV export in Flask
streaming
generators
csv
Intermediate
9 steps
php
<?php class ImageUploadService {
Validating file uploads safely in PHP
file-upload
input-validation
security
Intermediate
8 steps
python
import time from collections import defaultdict from threading import Lock
Sliding-window login rate limiting in Flask
rate-limiting
sliding-window
thread-safety
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.