Chapter 51 · Filtering, pagination, throttling, and API documentationCHAPTER 51
Complete six-part pre-release for review. Three packages: django-filter, drf-spectacular-sidecar, and httpx. Lists now carry next and previous beside results. Limits count per server process until Chapter 57.
Working towards: API and integrations (Chapter 54). Another program can list published events through an API and receive signed notifications when an event changes. All milestones
CHAPTER FIFTY-ONE
Filtering, pagination, throttling, and API documentation
Stage 6: APIs and real-time updates (Chapters 47 to 54)
Prerequisites: Chapters 9 to 50, including the Chapter 50 project with its 711 passing tests, personal access tokens with scopes, the generated OpenAPI file and its drift test from Chapter 49, and the problem-details handler from Chapter 48
What you’ll build: both lists paged by cursor, twenty events at a time; four filters on the public list, with a 422 that explains an unencoded +; limits on how often visitors, members, and tokens may call, answered with 429 and Retry-After; a documentation page for trying the API while developing; an httpx client that follows pages, waits when told to, and retries only reads; and the developers page with copyable examples
Why This Matters
The library in Leeds wants Otahque’s events on its own site. Its developer asks for the list and gets every event not yet ended, in one answer. Today that is a few dozen; after a year of weekly meetups in three cities it will be hundreds, and every page load at the library will fetch them all. The calendar club wants something narrower: published events with places left, next month only. And on a Tuesday night, one of Sam’s own scripts has a bug and asks for the list forty times a second, until everyone else’s pages slow down.
The API needs bounds. Answers of a known size, a page at a time. Questions a program can ask, so it fetches what it needs and nothing more. A limit on how often each caller may ask, so one broken script cannot crowd out the rest. And a description good enough that the library’s developer can try each operation before writing a line of code.
This chapter adds all four, with one change of shape that the contract already allowed: the lists gain next and previous beside results. It also writes the client a careful program would use, because a client that retries the wrong thing, or never waits, turns a small problem on the server into a large one.
By the end of the chapter, you will be able to:
explain why APIs page their lists, and why a cursor beats a page number when rows are being added;
add validated filters with django-filter, and turn bad values into precise 422 problems;
set throttle rates per kind of caller, and say where the counts live and what that means;
explain why + in a query string arrives as a space, and how a client should send an offset;
serve interactive API documentation in development only, from files the project serves itself;
write an HTTP client with timeouts, paging, and bounded retries of reads only, and test it without a server.
Out of scope: a shared cache for throttle counts across processes (Chapter 57), trusting a proxy’s client address (Chapter 63), generating client code from the OpenAPI file (not planned), and webhooks (Chapter 52).
An answer that grows with the database gets slower every month, uses more memory on both sides, and fails all at once when a client times out. Pagination splits a list into pages of a fixed size and tells the client how to get the next one. Two ways are common. Offset paging asks for “twenty, skipping the first forty” (?offset=40&limit=20, or page numbers, which are the same thing). Cursor paging asks for “twenty after this point”, where the point is the last row the client saw.
The difference shows when rows change between requests, as Otahque’s events do whenever an organizer publishes one. Figure 51.1 traces both, and the proof for L2 runs it.
Figure 51.1 — Offset pages and cursor pages, while an event is added.
New Concept: cursor pagination
What problem exists? A list that changes while a client reads it, page by page: offsets shift, so rows repeat or are skipped, and deep offsets make the database count past every skipped row.
What did people do before? Page numbers, as Otahque’s own HTML list has since Chapter 36, where a person rarely notices a repeat and wants to jump to page 5.
What is it? A cursor is an opaque value that marks where the last page ended. DRF’s CursorPagination encodes the last row’s position in the ordering, such as its start time, and the next query asks for rows after it. The client never builds a cursor; it follows the next address it was given.
Why use it? Programs read every page in order and must not miss or repeat an event. A cursor cannot drift, and the query uses an index however far in the client is. The cost: no jumping to page 7, and the ordering must be fixed and end in something unique.
Now let’s use it. Step 3 pages both lists by starts_at, then id, twenty at a time.
DRF’s cursor pagination has no page size the client can choose, so Otahque fixes it at twenty for both lists (D51.2). The organizer’s own list loses its “drafts first” order in the API, because a cursor needs one ordering for every page; the site’s My events page keeps it.
Filters
A filter narrows a list by the query string: ?has_places=true&status=published. The public list takes four, each optional (Table 51.1).
Table 51.1 — The public list’s filters
Parameter
Value
Example
starts_after
A time with its offset
2027-01-01T09:00:00Z
starts_before
A time with its offset
2027-02-01T00:00:00Z
has_places
true or false
true
status
published or cancelled
published
New Tool: django-filter
What problem exists? Each query parameter needs parsing, validating, an error for a bad value, a database lookup, and a line in the API’s documentation; written by hand, that is five places to keep in step per filter.
What did people do before?request.query_params.get() in the view, with try and except around each conversion, and an error format chosen by whoever wrote it.
What is it?django-filter declares filters as a FilterSet, much as a form declares fields: each filter names a model field and a lookup, and a bad value becomes a field error. Its DjangoFilterBackend plugs into DRF views, raises DRF’s ValidationError for invalid values, and drf-spectacular reads it to document each parameter. Version 26.2 supports Django 5.2 to 6.1.
Why use it? It is the filtering library DRF’s documentation points to, it reuses Django’s form fields, and its errors arrive at Otahque’s handler from Chapter 48, which already answers them as a 422 pointing at the parameter, such as #/starts_after (D51.1).
Now let’s use it. Step 4 writes EventFilter, with one field of Otahque’s own for times.
The plus sign in an address
Chapter 48 decided that a time must carry its offset, Z or +05:30, so it is never guessed. A query string has an old rule of its own: in HTML form encoding, + means a space. So ?starts_after=2027-01-01T09:00+05:30, typed into a browser or a script as it stands, reaches Django as 2027-01-01T09:00 05:30, with a space where the plus was. The parser cannot read it, and a generic “Enter a valid date/time” would leave the developer staring at a value that looks right. Otahque’s time field recognises that shape and says exactly what to do: write the plus as %2B, or give the time in UTC with Z (N51.7). A client library such as httpx encodes it by itself.
Under the Hood: how DRF throttles a request
APIView.initial() runs throttles last, after authentication and permissions, so a refused request never counts. Each class in DEFAULT_THROTTLE_CLASSES is asked allow_request(). A SimpleRateThrottle makes a cache key from its scope and the caller’s identity (an address, a member’s id, or here a token’s id), reads the list of times stored under it, drops those older than the window, and allows the request if fewer than the rate remain, appending now. If any class says no, DRF raises Throttled with the longest wait, and the response carries Retry-After. For visitors the identity is the client’s address: REMOTE_ADDR, or a value from X-Forwarded-For when NUM_PROXIES says how many proxies to trust. Left at its default, None, DRF takes X-Forwarded-For as the client sends it, so a script could claim a new address on every request. Otahque sets it to 0: there is no proxy until Chapter 63.
Limits per caller
A throttle (a rate limit) caps how many requests one caller may make in a period. Otahque’s rates are labelled assumptions, to be revisited with real use (D51.3): visitors 60 a minute, counted by address; members using the site 120; and each token 60 reads and 20 writes. A person clicking through pages stays far below them; a script in a loop does not. Figure 51.2 shows the path of one request.
Figure 51.2 — A request through the limits.
The counts live in Django’s default cache. Otahque has not configured one yet, so it is local memory, separate in each process: a server running four processes allows four times each rate. Chapter 57 moves the cache somewhere shared. Until then, a limit is a speed bump for runaway programs, not a wall, and DRF’s own documentation says the same of throttling in general: it is not a security measure against a determined attacker.
In practice: a partner’s nightly sync
Situation. The library’s site copies Otahque’s upcoming events every night into its own calendar.
Application. Its job asks for ?starts_after= the last night’s run, follows next until it is null, and reads Retry-After if it gets a 429. It sends a few requests a night, however large Otahque grows, and never repeats or misses an event when one is published mid-sync.
Consideration. A cursor is opaque and its format may change; the job stores the time of its last run, not a cursor, between nights. A change it must not miss, such as a cancellation, is better pushed to it as it happens: Chapter 52’s webhooks.
Documentation people can try
Chapter 49 made docs/api/openapi.yaml from the code. Tools can read it; people would rather click. Swagger UI turns an OpenAPI file into a page listing each operation, its parameters and answers, with a form to send a request and see the response. drf-spectacular serves it, and the companion package drf-spectacular-sidecar 2026.10.1 ships Swagger UI’s own files, so the page loads them from Otahque, not from a public CDN. Like DRF’s browsable pages, it exists only while DEBUG is on (N51.6); in production, the file and the developers page remain.
A client that behaves
Most of an API’s bad days are caused by clients: no timeout, so a slow request holds a worker forever; a retry loop with no pause, so a struggling server gets three times the traffic; a retried POST, so one draft becomes two. Otahque’s example client, examples/otahque_client.py, uses httpx 0.28.1 (N51.8), sets a timeout on every request, follows next, waits as Retry-After says, and retries a read at most three more times, after a timeout, a 429, or a 502, 503, or 504. It never retries a write: without an Idempotency-Key, which Otahque does not have (D48.1), the server cannot tell a retry from a second request.
New Tool: httpx
What problem exists? A program calling an API needs timeouts, connection reuse, query encoding, and a way to test its error handling without a live server.
What did people do before? Python’s urllib.request, as Sam’s script did in Chapter 50, which has a timeout but little else; or the requests library, with no built-in way to fake a server in tests.
What is it?httpx is an HTTP client for Python with a requests-like interface, explicit Timeout objects, connection pooling in a Client, and MockTransport, which answers requests from a function in the test itself. Version 0.28.1 (December 2024) is pinned; 0.29.0 appeared days before this chapter was checked, and is revisited at Chapter 53 or after its first patch. Chapter 53 kept 0.28.1, since 0.29.0 still had no patch release, and looks again at 0.29.1 or Chapter 62.
Why use it? Its MockTransport lets every retry rule be tested in milliseconds, and Chapter 52 uses the same library to deliver webhooks.
Now let’s use it. Step 7 writes the client and tests it against a mock server.
Start from Chapter 50, in the folder containing manage.py, with Otahque on PostgreSQL 18, 711 passing tests, and the work committed (the last commit is “Give programs tokens with scopes”). Three packages are added: django-filter 26.2, drf-spectacular-sidecar 2026.10.1, and httpx 0.28.1. There is no migration. New files: the pagination, filter, and throttle modules, a shared template for copyable commands, the example client, and three test modules. The settings, the API’s views and addresses, the developers page, the stylesheet, the contract, and the OpenAPI file change. The visible result: lists come twenty events at a time with next and previous; the public list takes four filters; a caller over its limit gets 429; /api/v1/docs/ shows Swagger UI while developing; and the developers page has copyable examples. The commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.
The Custom Way
The quickest paging a tutorial shows reads two numbers from the query string and slices:
It has every fault Figure 51.1 shows: an event published while a client reads page 1 shifts page 2, so one event appears twice and, when one is removed, another is never seen. A non-number in page is a 500, and nothing tells the client whether there is a next page. Filters written the same way repeat the parsing for every parameter, and a limit written by hand needs a counter shared by every request. This illustration is not added to the project.
The Django Way
The Django Way, with DRF, is to hand each concern to the class made for it: a pagination class, a FilterSet read by a filter backend, and throttle classes, all set on the view or in REST_FRAMEWORK, with the view’s own code reduced to “filter, page, answer”.
Step 1: Check the starting point
Terminal
uv run python manage.py test --parallel
Output
Found 711 test(s).
Creating test database for alias 'default'...
...
Ran 711 tests in ...s
OK
Resolved 57 packages in ...
Installed 1 package in ...
+ django-filter==26.2
Resolved 58 packages in ...
Installed 1 package in ...
+ drf-spectacular-sidecar==2026.10.1
Resolved 62 packages in ...
Installed 4 packages in ...
+ anyio==4.16.0
+ h11==0.16.0
+ httpcore==1.0.9
+ httpx==0.28.1
In config/settings.py, INSTALLED_APPS ends:
config/settings.py
'drf_spectacular',
# Chapter 51: the list's filters, and the files of the
# documentation page, served locally while developing.
'django_filters',
'drf_spectacular_sidecar',
httpx goes in the project’s main dependencies, not a development group, because Chapter 52’s webhooks send with it.
Step 3: Pages by cursor
The tests first. Create api/tests/test_lists.py; Step 4 adds its filters’ tests above PageTests, and Step 6 one more class at the end:
api/tests/test_lists.py
"""The lists' filters and pages (Chapter 51).
The public list takes four filters, each checked, and
both lists come twenty events a page, by cursor.
"""
from datetime import timedelta
from django.test import TestCase
from django.utils import timezone
from rest_framework.test import APIClient
from api.tests.test_mine import ready
from api.tests.test_writes import MINE
from config.helpers import in_group, save_event, save_events
from events.models import Event
from registrations.tests.test_waitlist import full
EVENTS = '/api/v1/events/'
def titles(page):
"""Return the titles on a page of the list."""
return [e['title'] for e in page.json()['results']]
and, after two blank lines:
api/tests/test_lists.py
class PageTests(TestCase):
"""Twenty a page, by cursor, for both lists."""
@classmethod
def setUpTestData(cls):
cls.first = timezone.now() + timedelta(days=1)
save_events(25, cls.first)
def test_twenty_then_five(self):
api = APIClient()
page = api.get(EVENTS).json()
self.assertEqual(len(page['results']), 20)
self.assertIsNone(page['previous'])
rest = api.get(page['next']).json()
self.assertEqual(len(rest['results']), 5)
self.assertIsNone(rest['next'])
self.assertIsNotNone(rest['previous'])
def test_an_event_added_meanwhile_repeats_nothing(self):
api = APIClient()
page = api.get(EVENTS)
# A new event that sorts on the first page, before
# the cursor: page numbers would now repeat one.
save_event(title='Event 000',
starts_at=self.first - timedelta(hours=1))
rest = api.get(page.json()['next'])
seen = titles(page) + titles(rest)
self.assertEqual(len(seen), len(set(seen)))
self.assertEqual(seen[-1], 'Event 025')
def test_my_events_are_paged_too(self):
sam = in_group('sam@example.org', 'Organizers')
for n in range(21):
ready(title=f'Draft {n:02}').add_organizer(sam)
api = APIClient()
api.force_login(sam)
page = api.get(MINE).json()
self.assertEqual(len(page['results']), 20)
self.assertIsNotNone(page['next'])
def test_a_made_up_cursor_is_404(self):
page = APIClient().get(f'{EVENTS}?cursor=nonsense')
self.assertEqual(page.status_code, 404)
self.assertEqual(page['Content-Type'],
'application/problem+json')
test_an_event_added_meanwhile_repeats_nothing is Figure 51.1 as a test: an event that sorts onto page 1 is saved between the two requests, and no title may appear twice.
Terminal
uv run python manage.py test api.tests.test_lists
Output
Found 4 test(s).
Creating test database for alias 'default'...
ERROR: test_an_event_added_meanwhile_repeats_nothing
KeyError: 'next'
FAIL: test_a_made_up_cursor_is_404
AssertionError: 200 != 404
FAIL: test_my_events_are_paged_too
AssertionError: 21 != 20
... (1 more like these)
Ran 4 tests in ...s
FAILED (failures=3, errors=1)
Create api/pagination.py:
api/pagination.py
"""Pages of events, by cursor (Chapter 51)."""
from rest_framework.pagination import CursorPagination
class EventCursor(CursorPagination):
"""Twenty events a page, soonest first, by cursor.
next and previous are full addresses holding an opaque
cursor: where the last page ended, not a page number,
so an event added meanwhile never repeats or hides one.
The order ends with id, which no two events share.
"""
page_size = 20
ordering = ('starts_at', 'id')
In api/views.py, inline_serializer is no longer needed, so the drf-spectacular import becomes:
api/views.py
from drf_spectacular.utils import (
OpenApiParameter, OpenApiResponse, extend_schema,
extend_schema_view,
)
add, above from .permissions import TokenScope:
api/views.py
from .pagination import EventCursor
and EventList becomes:
api/views.py
class EventList(PublicRead):
"""Published and cancelled events not yet ended.
Chapter 51: paged by cursor, twenty at a time
(EventCursor).
"""
pagination_class = EventCursor
def get_queryset(self):
"""Return the events the list starts from."""
return upcoming()
@extend_schema(
operation_id='listEvents',
summary='List events that have not ended yet.',
responses={200: EventSerializer(many=True),
405: PROBLEM, 406: PROBLEM,
422: INVALID})
def get(self, request):
"""Send one page: next, previous, and results."""
events = self.get_queryset()
page = self.paginate_queryset(events)
data = self.get_serializer(page, many=True).data
return self.get_paginated_response(data)
get_queryset() replaces calling upcoming() inside get(), so filters and drf-spectacular find the queryset where DRF looks for it. paginate_queryset() asks the pagination class for one page, and get_paginated_response() wraps it with next and previous. The 422 in the description is for Step 4’s filters.
The organizer’s list is paged the same way. In the viewset’s decorator, its list entry becomes:
api/views.py
operation_id='listMyEvents',
summary='List the events you organize, drafts too.',
responses={200: MyEventSerializer(many=True),
401: NO_TOKEN, 403: PROBLEM}),
the viewset’s first lines:
api/views.py
serializer_class = MyEventSerializer
# Chapter 51: paged as the public list is, soonest first.
pagination_class = EventCursor
and its list():
api/views.py
def list(self, request):
"""GET: a page of my events; 403 for members."""
if not request.user.has_perm('events.change_event'):
raise exceptions.PermissionDenied(
'Only organizers have events here.')
page = self.paginate_queryset(self.get_queryset())
data = self.get_serializer(page, many=True).data
return self.get_paginated_response(data)
Terminal
uv run python manage.py test api.tests.test_lists
Output
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s
OK
Common Error: a cursor on a column that repeats
ordering = ('starts_at',) alone looks enough, until two events start at the same minute, which a weekly series makes likely. DRF’s cursor then has to count past the ties, and a page boundary inside them can repeat or skip an event. End the ordering with a column no two rows share, here id.
test_an_unencoded_plus_is_explained sends the same time twice, once with a raw + and once with %2B: the first must say how to fix it, and the second must work.
Terminal
uv run python manage.py test api.tests.test_lists
Output
Found 11 test(s).
Creating test database for alias 'default'...
ERROR: test_an_unencoded_plus_is_explained
KeyError: 'errors'
FAIL: test_a_time_needs_an_offset
AssertionError: 200 != 422
FAIL: test_bad_values_are_422_by_parameter
AssertionError: 200 != 422
... (3 more like these)
Ran 11 tests in ...s
FAILED (failures=5, errors=1)
The filters ran nowhere, so every query returned the whole list. Create api/filters.py:
api/filters.py
"""What a program may ask the event list for (Chapter 51).
django-filter reads the query string into a form, so a bad
value is a field error; its DRF backend raises DRF's
ValidationError, which Otahque's handler answers as a 422
pointing at the parameter, such as #/starts_after.
"""
import re
import django_filters as filters
from django import forms
from django.core.exceptions import ValidationError
from django.utils.dateparse import parse_datetime
from events.models import Event
# A + in an address means a space (HTML forms' rule), so an
# unencoded +05:30 arrives as " 05:30".
SPACE_FOR_PLUS = re.compile(r'\d \d{2}:\d{2}$')
class OffsetDateTimeField(forms.DateTimeField):
"""A time with its offset, never guessed (Chapter 48)."""
def to_python(self, value):
"""Return an aware datetime, or say what to fix."""
if value in self.empty_values:
return None
if SPACE_FOR_PLUS.search(value):
raise ValidationError(
'A + in an address arrives as a space. Encode '
'it as %%2B, or give the time in UTC with Z.')
try:
moment = parse_datetime(value)
except ValueError:
moment = None
if moment is None:
raise ValidationError(
'Enter a time such as 2026-12-10T18:00:00Z.')
if moment.tzinfo is None:
raise ValidationError(
'Add an offset to the time: Z or +05:30.')
return moment
class OffsetDateTimeFilter(filters.Filter):
"""Filter on a time that must carry its offset."""
field_class = OffsetDateTimeField
class EventFilter(filters.FilterSet):
"""The public list's four filters; all are optional."""
starts_after = OffsetDateTimeFilter(
field_name='starts_at', lookup_expr='gte',
label='Starts at or after this time.')
starts_before = OffsetDateTimeFilter(
field_name='starts_at', lookup_expr='lt',
label='Starts before this time.')
has_places = filters.ChoiceFilter(
choices=[('true', 'true'), ('false', 'false')],
method='by_places',
label='true: places left; false: full.')
status = filters.ChoiceFilter(
choices=[(s, s) for s in ('published', 'cancelled')],
label='published or cancelled.')
class Meta:
model = Event
fields = []
def by_places(self, queryset, name, value):
"""Keep events with places left, or only full ones."""
if value == 'true':
return queryset.filter(places_left__gt=0)
return queryset.filter(places_left__lte=0)
OffsetDateTimeField replaces Django’s own date-time form field, which would read a time without an offset in the current time zone, the guess Chapter 48 refused. %%2B in its message is %2B once Django fills in the message’s parameters. has_places is a ChoiceFilter, not a BooleanFilter, because the latter quietly ignores a value it cannot read, and a program that sends has_places=yes should hear about it.
In api/views.py, add below from django.views.decorators.http import require_safe:
api/views.py
from django_filters.rest_framework import DjangoFilterBackend
and above from .pagination import EventCursor:
api/views.py
from .filters import EventFilter
EventList then reads:
api/views.py
class EventList(PublicRead):
"""Published and cancelled events not yet ended.
Chapter 51: filtered by the query string (EventFilter),
and paged by cursor, twenty at a time (EventCursor).
"""
filter_backends = [DjangoFilterBackend]
filterset_class = EventFilter
pagination_class = EventCursor
def get_queryset(self):
"""Return the events the list starts from."""
return upcoming()
@extend_schema(
operation_id='listEvents',
summary='List events that have not ended yet.',
responses={200: EventSerializer(many=True),
405: PROBLEM, 406: PROBLEM,
422: INVALID})
def get(self, request):
"""Send one page: next, previous, and results."""
events = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(events)
data = self.get_serializer(page, many=True).data
return self.get_paginated_response(data)
Terminal
uv run python manage.py test api.tests.test_lists
Output
Found 11 test(s).
Creating test database for alias 'default'...
...
Ran 11 tests in ...s
OK
Step 5: Limits
The tests, in api/tests/test_throttles.py:
api/tests/test_throttles.py
"""How often each kind of caller may call (Chapter 51).
Counts live in the cache, so each test starts and ends
with it empty: no count leaks into another test.
"""
from django.core.cache import cache
from django.test import TestCase
from rest_framework.test import APIClient
from api.models import PersonalAccessToken as Token
from api.tests.test_mine import ready
from api.tests.test_tokens import bearer
from api.tests.test_writes import MINE
from config.helpers import in_group
EVENTS = '/api/v1/events/'
class ThrottleTests(TestCase):
"""Visitors, members, and tokens, each at their rate."""
@classmethod
def setUpTestData(cls):
cls.sam = in_group('sam@example.org', 'Organizers')
def setUp(self):
cache.clear()
self.addCleanup(cache.clear)
def last_of(self, count, send):
"""Send count requests; return the last answer."""
for _ in range(count):
answer = send()
return answer
def test_a_visitor_gets_60_a_minute(self):
api = APIClient()
self.assertEqual(
self.last_of(60, lambda: api.get(EVENTS))
.status_code, 200)
page = api.get(EVENTS)
self.assertEqual(page.status_code, 429)
self.assertTrue(page['Retry-After'].isdigit())
self.assertEqual(page['Content-Type'],
'application/problem+json')
def test_a_claimed_address_changes_nothing(self):
api = APIClient()
self.last_of(60, lambda: api.get(EVENTS))
page = api.get(EVENTS, headers={
'X-Forwarded-For': '203.0.113.9'})
self.assertEqual(page.status_code, 429)
other = APIClient(REMOTE_ADDR='198.51.100.7')
self.assertEqual(other.get(EVENTS).status_code, 200)
def test_a_member_gets_120_a_minute(self):
api = APIClient()
api.force_login(self.sam)
self.last_of(120, lambda: api.get(MINE))
self.assertEqual(api.get(MINE).status_code, 429)
def test_a_tokens_writes_and_reads_count_apart(self):
event = ready(title='Clinic')
event.add_organizer(self.sam)
api = bearer(Token.issue(self.sam, 'agent',
['read', 'write'])[1])
def write():
"""Send a dry-run change: a write, saving nothing."""
return api.patch(
f'{MINE}{event.pk}/?dry_run=true',
{'title': 'New'}, format='json',
headers={'If-Match': '"v1"'})
self.assertEqual(self.last_of(20, write).status_code,
200)
self.assertEqual(write().status_code, 429)
self.assertEqual(api.get(MINE).status_code, 200)
def test_each_token_has_its_own_count(self):
first = bearer(Token.issue(self.sam, 'a', ['read'])[1])
second = bearer(Token.issue(self.sam, 'b', ['read'])[1])
self.last_of(60, lambda: first.get(MINE))
self.assertEqual(first.get(MINE).status_code, 429)
self.assertEqual(second.get(MINE).status_code, 200)
Each test empties the cache before and after itself, so its counts never reach another test. The rest of the suite needs no such care: counted across every test, it sends fewer API requests than any limit allows, even in one process. test_a_claimed_address_changes_nothing sends X-Forwarded-For with a made-up address and is still refused; a second client with its own REMOTE_ADDR is not.
Terminal
uv run python manage.py test api.tests.test_throttles
Output
Found 5 test(s).
Creating test database for alias 'default'...
FAIL: test_a_claimed_address_changes_nothing
AssertionError: 200 != 429
FAIL: test_a_member_gets_120_a_minute
AssertionError: 200 != 429
FAIL: test_a_tokens_writes_and_reads_count_apart
AssertionError: 200 != 429
... (2 more like these)
Ran 5 tests in ...s
FAILED (failures=5)
Create api/throttles.py:
api/throttles.py
"""How often each kind of caller may use the API (Chapter 51).
The rates are in REST_FRAMEWORK's DEFAULT_THROTTLE_RATES.
Counts live in the default cache: until Chapter 57, local
memory in each process, so two server processes each allow
the full rate. A limit slows a runaway program; it is not
protection against an attack.
"""
from rest_framework.permissions import SAFE_METHODS
from rest_framework.throttling import (
AnonRateThrottle, SimpleRateThrottle,
)
from .models import PersonalAccessToken
def by_token(request):
"""Return the request's token, or None for a session."""
if isinstance(request.auth, PersonalAccessToken):
return request.auth
return None
class VisitorRate(AnonRateThrottle):
"""Visitors, counted by address: NUM_PROXIES says how."""
scope = 'visitor'
class MemberRate(SimpleRateThrottle):
"""Signed-in members using the site's session."""
scope = 'member'
def get_cache_key(self, request, view):
"""Count per member; tokens and visitors are not ours."""
user = request.user
if by_token(request) or not user.is_authenticated:
return None
return self.cache_format % {
'scope': self.scope, 'ident': user.pk}
class TokenReadRate(SimpleRateThrottle):
"""Programs with a token: their reads, GET and HEAD."""
scope = 'token_read'
counts_reads = True
def get_cache_key(self, request, view):
"""Count per token; other requests are not ours."""
token = by_token(request)
is_read = request.method in SAFE_METHODS
if token is None or is_read != self.counts_reads:
return None
return self.cache_format % {
'scope': self.scope, 'ident': token.pk}
class TokenWriteRate(TokenReadRate):
"""Programs with a token: their writes, at a lower rate."""
scope = 'token_write'
counts_reads = False
MemberRate and the two token classes return None from get_cache_key() for requests that are not theirs, which DRF reads as “not counted here”. A token’s reads and writes have separate counts, so an agent that hits its write limit can still read.
In config/settings.py, add to REST_FRAMEWORK, above its Chapter 49 comment:
config/settings.py
# Chapter 51: how often each kind of caller may call.
# The rates are assumptions, to revisit with real use:
# a person clicking stays far below them; a script in a
# loop does not. Over a rate: 429 with Retry-After.
'DEFAULT_THROTTLE_CLASSES': [
'api.throttles.VisitorRate',
'api.throttles.MemberRate',
'api.throttles.TokenReadRate',
'api.throttles.TokenWriteRate',
],
'DEFAULT_THROTTLE_RATES': {
'visitor': '60/min',
'member': '120/min',
'token_read': '60/min',
'token_write': '20/min',
},
# Visitors are counted by REMOTE_ADDR. 0 means no proxy
# sets X-Forwarded-For; DRF's default, None, would trust
# whatever address a client claims. Chapter 63 sets it.
'NUM_PROXIES': 0,
Terminal
uv run python manage.py test api.tests.test_throttles
Output
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s
OK
Common Error: NUM_PROXIES left unset
With NUM_PROXIES missing, DRF counts visitors by the first address in X-Forwarded-For whenever a client sends one. Any script can then send a new made-up address with every request and never be limited. Set it to the number of proxies you run, 0 until Chapter 63, and test it, as test_a_claimed_address_changes_nothing does.
Step 6: The documentation page
Add the last test class to the end of test_lists.py:
api/tests/test_lists.py
class DocsPageTests(TestCase):
"""The documentation page, while developing only."""
def test_it_is_not_served_with_debug_off(self):
# Tests run with DEBUG off, as production does.
page = APIClient().get('/api/v1/docs/')
self.assertEqual(page.status_code, 404)
It passes already, and must keep passing: tests run with DEBUG off, as production does, so the page must not exist there. In config/settings.py, the OpenAPI description now mentions pages and limits:
config/settings.py
'DESCRIPTION': (
"Read Otahque's published and cancelled events; "
'manage your own events if you organize them. Times '
"are UTC; show them in each event's timezone. Lists "
'come a page at a time: follow next. Each kind of '
'caller has a rate limit; over it, 429 with '
'Retry-After. The rules are in docs/api/contract.md.'),
and SPECTACULAR_SETTINGS ends:
config/settings.py
# Chapter 51: the documentation page's files come from
# drf-spectacular-sidecar, served by Otahque itself, not
# from a public CDN.
'SWAGGER_UI_DIST': 'SIDECAR',
'SWAGGER_UI_FAVICON_HREF': 'SIDECAR',
api/urls.py becomes:
api/urls.py
"""Addresses of the API, under /api/v1/ (Chapters 47 to 51)."""
from django.conf import settings
from django.urls import path
from drf_spectacular.views import SpectacularSwaggerView
from rest_framework.routers import SimpleRouter
from . import views
app_name = 'api'
# Chapter 49: the router gives the viewset's actions their
# addresses: my/events/, my/events/{id}/, and .../publish/
# and .../cancel/ for the two @action methods.
router = SimpleRouter()
router.register('my/events', views.MyEventViewSet,
basename='my_event')
urlpatterns = [
path('events/', views.event_list, name='event_list'),
path('events/<int:event_id>/', views.event_detail,
name='event_detail'),
*router.urls,
path('openapi.yaml', views.openapi, name='openapi'),
]
# Chapter 51: a page to read and try each operation, made
# by Swagger UI from openapi.yaml; while developing only,
# like DRF's browsable pages.
if settings.DEBUG:
urlpatterns.append(path(
'docs/', SpectacularSwaggerView.as_view(
url_name='api:openapi'), name='docs'))
urlpatterns += [
# Last: anything else under /api/v1/ is a 404 in JSON,
# never the site's HTML page.
path('<path:rest>', views.not_found, name='not_found'),
]
The page is added only when DEBUG is on, and before the catch-all, which must stay last. It reads the same openapi.yaml that programs download.
Terminal
uv run python manage.py test api.tests.test_lists
Output
Found 12 test(s).
Creating test database for alias 'default'...
...
Ran 12 tests in ...s
OK
The paging and filters changed what the OpenAPI file should say, and Chapter 49’s drift test says so:
Terminal
uv run python manage.py test api.tests.test_openapi
Output
Found 7 test(s).
Creating test database for alias 'default'...
FAIL: test_the_file_is_what_the_code_makes
AssertionError: b'ope[70 chars]ion: Read Otahque\'s published
and cancelled e[22847 chars]v1\n' != b'ope[70 chars]ion:
\'Read Otahque\'\'s published and cancell[25052
chars]v1\n' : Run: uv run python manage.py spectacular
--file docs/api/openapi.yaml
Ran 7 tests in ...s
FAILED (failures=1)
Terminal
uv run python manage.py spectacular --file docs/api/openapi.yaml
uv run python manage.py test api.tests.test_openapi
Output
Found 7 test(s).
Creating test database for alias 'default'...
...
Ran 7 tests in ...s
OK
Read the diff of docs/api/openapi.yaml: listEvents gains its four filters and cursor, each with its type, and both lists answer PaginatedEventList or PaginatedMyEventList, with next and previous.
Step 7: The client
Its tests come first, in api/tests/test_client.py. They run no server: httpx’s MockTransport hands each request to a function in the test, which records it and returns the next prepared answer.
api/tests/test_client.py
"""The example client, against httpx's MockTransport (51).
No server runs: each test's handler answers the requests
the client sends, and records them, so a test can count
the tries and read the address that was sent.
"""
import httpx
from django.test import SimpleTestCase
from examples.otahque_client import Otahque
BASE = 'http://otahque.test'
def page(titles, next_url=None):
"""Return a list page's JSON body."""
return {'next': next_url, 'previous': None,
'results': [{'title': t} for t in titles]}
class ClientTests(SimpleTestCase):
"""Paging, waiting, and retrying only what is safe."""
def api_with(self, *answers):
"""Return a client whose server gives answers in turn.
Each answer is a response, or an exception to raise.
"""
self.sent, self.slept = [], []
queue = list(answers)
def handle(request):
"""Record the request; give the next answer."""
self.sent.append(request)
answer = queue.pop(0)
if isinstance(answer, Exception):
raise answer
return answer
return Otahque(BASE, 'otq_test',
transport=httpx.MockTransport(handle),
sleep=self.slept.append)
def test_it_follows_next_to_the_end(self):
api = self.api_with(
httpx.Response(200, json=page(
['A', 'B'], f'{BASE}/api/v1/events/?cursor=x')),
httpx.Response(200, json=page(['C'])))
titles = [e['title'] for e in api.events()]
self.assertEqual(titles, ['A', 'B', 'C'])
self.assertEqual(self.sent[1].url.params['cursor'], 'x')
def test_the_token_and_an_encoded_plus_are_sent(self):
api = self.api_with(httpx.Response(200, json=page([])))
list(api.events(starts_after='2027-01-01T09:00+05:30'))
request = self.sent[0]
self.assertEqual(request.headers['Authorization'],
'Bearer otq_test')
self.assertIn(b'%2B05%3A30', request.url.query)
def test_429_waits_as_told(self):
api = self.api_with(
httpx.Response(429, headers={'Retry-After': '7'}),
httpx.Response(200, json=page(['A'])))
self.assertEqual(len(list(api.events())), 1)
self.assertEqual(self.slept, [7])
def test_timeouts_and_503_are_tried_four_times(self):
api = self.api_with(httpx.ReadTimeout('slow'),
httpx.Response(503),
httpx.Response(502),
httpx.Response(504))
with self.assertRaises(httpx.HTTPStatusError):
list(api.events())
self.assertEqual(len(self.sent), 4)
self.assertEqual(self.slept, [1, 2, 4])
def test_other_errors_are_not_retried(self):
api = self.api_with(httpx.Response(404))
with self.assertRaises(httpx.HTTPStatusError):
api.get('/api/v1/events/99/')
self.assertEqual(len(self.sent), 1)
def test_a_write_is_sent_once(self):
api = self.api_with(httpx.Response(503))
with self.assertRaises(httpx.HTTPStatusError):
api.change(7, 3, title='New')
self.assertEqual(len(self.sent), 1)
self.assertEqual(self.sent[0].headers['If-Match'],
'"v3"')
Terminal
uv run python manage.py test api.tests.test_client
Output
Found 1 test(s).
ERROR: test_client (unittest.loader._FailedTest.test_client)
ImportError: Failed to import test module: test_client
ModuleNotFoundError: No module named
'examples.otahque_client'
Ran 1 test in ...s
FAILED (errors=1)
Create examples/otahque_client.py. Its top:
examples/otahque_client.py
"""A small client for Otahque's API, with httpx (Chapter 51).
It reads every page of a list, waits when told to, and
retries a read that timed out or met a busy server, a few
times at most. It never retries a write: Otahque has no
Idempotency-Key, so a repeated POST could make two drafts.
from examples.otahque_client import Otahque
with Otahque('http://127.0.0.1:8000', token) as api:
for event in api.events(has_places='true'):
print(event['title'])
"""
import os
import time
import httpx
# Statuses worth asking again: too many requests, and a
# server or proxy that is busy or briefly down.
RETRY = {429, 502, 503, 504}
# At most 5 seconds to connect, 10 for anything else.
TIMEOUT = httpx.Timeout(10.0, connect=5.0)
def wait_after(answer, attempt):
"""Return the seconds to wait before the next try.
Retry-After, when the server sends it as seconds; else
1, 2, 4, ... seconds, never more than 30.
"""
given = answer.headers.get('Retry-After', '')
if given.isdigit():
return int(given)
return min(2 ** (attempt - 1), 30)
the client, after two blank lines:
examples/otahque_client.py
class Otahque:
"""Otahque's API, read and written as a program should."""
def __init__(self, base_url, token=None, *, tries=4,
transport=None, sleep=time.sleep):
"""Open a client; a token is needed for my/events.
transport and sleep are for tests: httpx's
MockTransport answers without a server, and a fake
sleep keeps waiting out of the test run.
"""
headers = {'Accept': 'application/json'}
if token:
headers['Authorization'] = f'Bearer {token}'
self.http = httpx.Client(
base_url=base_url, headers=headers,
timeout=TIMEOUT, transport=transport)
self.tries = tries
self.sleep = sleep
def __enter__(self):
"""Use the client in a with block."""
return self
def __exit__(self, *exc):
"""Close its connections at the end of the block."""
self.http.close()
def get(self, path, params=None):
"""GET path; retry a timeout, 429, or 502 to 504.
Gives up after self.tries attempts, raising the last
error; any other 4xx or 5xx raises at once.
"""
for attempt in range(1, self.tries + 1):
last = attempt == self.tries
try:
answer = self.http.get(path, params=params)
except httpx.TimeoutException:
if last:
raise
self.sleep(min(2 ** (attempt - 1), 30))
continue
if answer.status_code in RETRY and not last:
self.sleep(wait_after(answer, attempt))
continue
answer.raise_for_status()
return answer.json()
def events(self, **filters):
"""Yield every listed event, following next to the end.
Filters go in the query string; httpx encodes them,
so the + of +05:30 is sent as %2B.
"""
page = self.get('/api/v1/events/', params=filters)
while True:
yield from page['results']
if page['next'] is None:
return
page = self.get(page['next'])
def change(self, event_id, version, **fields):
"""PATCH one of my events, once; never retried."""
answer = self.http.patch(
f'/api/v1/my/events/{event_id}/', json=fields,
headers={'If-Match': f'"v{version}"'})
answer.raise_for_status()
return answer.json()
and a small program to run it, at the end:
examples/otahque_client.py
def main():
"""Print upcoming events with places, from OTAHQUE_URL."""
with Otahque(os.environ['OTAHQUE_URL']) as api:
for event in api.events(has_places='true'):
print(event['starts_at'][:10], event['title'])
if __name__ == '__main__':
main()
get() is the only method that retries, and it retries only what is safe to repeat. change() sends once and raises on any error: the caller decides, perhaps by reading the event again first. wait_after() prefers the server’s Retry-After to its own guess.
Terminal
uv run python manage.py test api.tests.test_client
Output
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s
OK
Run the server, and in a second terminal run the client.
PowerShell:
Windows PowerShell
$env:OTAHQUE_URL = 'http://127.0.0.1:8000'
uv run python examples/otahque_client.py
macOS, Linux, or WSL:
Git Bash, macOS, or Linux
export OTAHQUE_URL='http://127.0.0.1:8000'
uv run python examples/otahque_client.py
Your list shows your own events with places left. Stop the server when it has finished.
Common Error: retrying a POST or PATCH
A retry after a timeout feels safe, but the first request may have reached the server and succeeded before the answer was lost. A second POST then makes a second draft; a second PATCH fails with 412, because the first one changed the version. Retry writes only when the API offers an idempotency key; Otahque’s does not, so change() never retries.
Step 8: The developers page
The UI increment shows the new rules where developers look first, with commands they can copy. In api/views.py, developers() passes a filtered example and whether the documentation page exists:
api/views.py
events = absolute(reverse('api:event_list'))
return render(request, 'api/developers.html', {
'example': f'curl {events}',
# Chapter 51: a filtered list, with the + of an
# offset written %2B, as an address needs it.
'filtered': (f'curl "{events}?has_places=true'
'&starts_after=2027-01-01T09:00%2B05:30"'),
'docs': settings.DEBUG,
The shared improvement is a template any page can use for a command with a Copy button, built on Chapter 49’s copy script. Create templates/includes/copy.html:
templates/includes/copy.html
{# Chapter 51: a command or listing with a Copy button, #}
{# for any page. Give it id and code, with {% with %}. #}
<div class="code-copy">
<pre><code id="{{ id }}">{{ code }}</code></pre>
<button type="button" class="btn btn-ghost btn-xs needs-js"
data-copy="{{ id }}" data-copied="Command copied.">
Copy</button>
</div>
In api/templates/api/developers.html, the list’s description says it is paged:
api/templates/api/developers.html
<dd>Published and cancelled events not yet ended,
soonest first, twenty a page: follow
<code>next</code> until it is null.</dd>
<dt><code>GET /api/v1/events/{id}/</code></dt>
<dd>One event. A draft, or an id that does not
exist, is 404.</dd>
the example becomes a copyable block, followed by two new cards:
api/templates/api/developers.html
{% with id="example" code=example %}
{% include "includes/copy.html" %}
{% endwith %}
</section>
{# Chapter 51: filters, with an encoded offset. #}
<section class="dev-card" aria-labelledby="dev-filter">
<h2 id="dev-filter">Only what you need</h2>
<dl class="dev-endpoints">
<dt><code>starts_after</code>,
<code>starts_before</code></dt>
<dd>A time with its offset: <code>Z</code>, or
<code>%2B05:30</code> in an address, since a
plain <code>+</code> arrives as a space.</dd>
<dt><code>has_places</code></dt>
<dd><code>true</code> or <code>false</code>.</dd>
<dt><code>status</code></dt>
<dd><code>published</code> or
<code>cancelled</code>.</dd>
</dl>
{% with id="filtered" code=filtered %}
{% include "includes/copy.html" %}
{% endwith %}
</section>
<section class="dev-card" aria-labelledby="dev-limits">
<h2 id="dev-limits">Limits</h2>
<p>Each kind of caller may make a number of requests
a minute: visitors 60, members 120, and each token
60 reads and 20 writes. Over a limit, the answer is
429: wait the seconds <code>Retry-After</code>
says, then try again.</p>
</section>
and the contract card gains the documentation link, shown only while developing:
api/templates/api/developers.html
<section class="dev-card" aria-labelledby="dev-contract">
<h2 id="dev-contract">The contract</h2>
<p>Every field, error, and header is described in
OpenAPI 3.1, which tools and AI agents can read.</p>
<p class="flex flex-wrap gap-2">
<a class="btn btn-primary btn-sm"
href="{% url 'api:openapi' %}">Download
openapi.yaml</a>
{% if docs %}
<a class="btn btn-sm" href="{% url 'api:docs' %}">
Try it (development only)</a>
{% endif %}
</p>
</section>
In static/otahque/source.css, the .dev-example rule is replaced by the shared one:
static/otahque/source.css
/* Chapter 51: a command with a Copy button, for any page
(templates/includes/copy.html); it replaces the
developers page's .dev-example. */
.code-copy {
position: relative;
border-radius: var(--radius-field);
background-color: var(--color-neutral);
color: var(--color-neutral-content);
}
.code-copy pre {
padding: 0.75rem 4.5rem 0.75rem 0.75rem;
font-size: 0.875rem;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.code-copy button {
position: absolute;
top: 0.375rem;
right: 0.375rem;
color: inherit;
}
Terminal
npm run build
uv run python manage.py test api
Step 9: The contract
In docs/api/contract.md, the list’s paragraph is replaced by:
docs/api/contract.md
The list holds published and cancelled events whose end
is still to come, soonest start first. A draft is never
listed, and its id answers 404, the same as an id that
does not exist.
## Pages and filters (Chapter 51)
Both lists come twenty events a page, as `{"next": ...,
"previous": ..., "results": [...]}`. `next` and
`previous` are full addresses, or null at either end;
follow them as they are. Their `cursor` is opaque: it
marks where a page ended, so an event added or removed
meanwhile never repeats or skips one. A cursor that is
not one of ours is 404.
The public list takes four filters, all optional:
| Parameter | Value |
|---|---|
| `starts_after` | A time with its offset; at or after it |
| `starts_before` | A time with its offset; before it |
| `has_places` | `true` or `false` |
| `status` | `published` or `cancelled` |
In an address, write the `+` of an offset as `%2B`
(`09:00%2B05:30`), or give the time in UTC with `Z`: a
plain `+` arrives as a space, and is refused with a 422
that says so. Any bad value is a 422 pointing at its
parameter, such as `#/starts_after`.
## Limits (Chapter 51)
Each kind of caller may make a number of requests a
minute: visitors 60 (counted by address), members 120,
and each token 60 reads and 20 writes. These are first
assumptions, to be revisited with real use. Over a limit,
the answer is 429 with `Retry-After`, the seconds to
wait. Limits slow a runaway program; they do not stop an
attack.
and the error table gains a row:
docs/api/contract.md
| 428 | A write without `If-Match` |
| 429 | Too many requests; wait `Retry-After` seconds |
Step 10: In a browser
Run the server and open http://127.0.0.1:8000/developers/. Press Copy beside the filtered example, then Try it (development only). Figure 51.3 shows both pages.
Figure 51.3 — The developers page, and the documentation page while developing.
Open GET /events/, press Try it out, set has_places to true, and Execute: the page shows the address it called, with each value encoded, and the answer with next. Every file the page loads comes from Otahque itself.
Step 11: The checks, and the commit
Stop the server, then:
Terminal
uv run python check.py
Output
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
No changes detected
== python manage.py test --parallel
Found 734 test(s).
System check identified no issues (0 silenced).
Ran 734 tests in ...s
OK
== all checks passed
Terminal
git add .
git status --short
git commit -m "Page, filter, and limit the API; add docs"
Output
A api/filters.py
A api/pagination.py
M api/templates/api/developers.html
A api/tests/test_client.py
A api/tests/test_lists.py
A api/tests/test_throttles.py
A api/throttles.py
M api/urls.py
M api/views.py
M config/settings.py
M docs/api/contract.md
M docs/api/openapi.yaml
A examples/otahque_client.py
M pyproject.toml
M static/otahque/site.css
M static/otahque/source.css
A templates/includes/copy.html
M uv.lock
[main 1a2b3c4] Page, filter, and limit the API; add docs
18 files changed, 971 insertions(+), 51 deletions(-)
create mode 100644 api/filters.py
create mode 100644 api/pagination.py
create mode 100644 api/tests/test_client.py
create mode 100644 api/tests/test_lists.py
create mode 100644 api/tests/test_throttles.py
create mode 100644 api/throttles.py
create mode 100644 examples/otahque_client.py
create mode 100644 templates/includes/copy.html
Work through Table 51.3 from the folder that holds manage.py, with Otahque on PostgreSQL.
Table 51.3 — Verification checklist for Chapter 51
Check
Command or action
Expected result
Starting point
test --parallel
Found 711 test(s); OK
Packages
uv add, three times
django-filter, the sidecar, and httpx added
Pages
test api.tests.test_lists
Red first; then 4 tests OK
Filters
the same
Red first; then 11 tests OK
Limits
test api.tests.test_throttles
Red first; then 5 tests OK
Docs page and OpenAPI
test_lists; test_openapi; spectacular --file
12 tests OK; red until the file is made; then 7 OK
The client
test api.tests.test_client; the client against the server
ImportError first; then 6 tests OK; your events with places
Developers page
test api
OK
In a browser
/developers/ and /api/v1/docs/ at 390 and 1280 px
Copied; Swagger UI from Otahque's own files
All checks
uv run python check.py
== all checks passed; Ran 734 tests
Commit
git log --oneline -1
Page, filter, and limit the API; add docs
Not verified
Limits across several server processes; macOS and Linux shells
Expected per process until Chapter 57
The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 50 checkpoint with a reader’s data, against PostgreSQL 18; commands that write files ran once. In Microsoft Edge, at 390 and 1280 pixels, a Playwright script opened the developers page, pressed Copy beside the filtered example and read the clipboard back (it held the command, with %2B05:30), followed Try it to the documentation page, found the public list and the organizer’s list among its operations, and recorded the host of every file the browser fetched: all came from the development server. There was no sideways scroll, and every control had a name.
Que. 1 Why does Otahque page its API lists by cursor, when its HTML list uses page numbers?
Flip to check your answerFold answer back
Answer. Programs read every page in order and must not repeat or miss an event, even when one is published meanwhile; a cursor marks where the last page ended, so rows added before it cannot shift the next page. People on the HTML list want to jump to a page, which a cursor cannot do.
Que. 2 A client sends ?starts_after=2027-01-01T09:00+05:30 without encoding it. What happens?
Flip to check your answerFold answer back
Answer. The + arrives as a space, and Otahque answers 422 pointing at #/starts_after, saying to send %2B or the time in UTC with Z.
Que. 3 Where do throttle counts live, and what does that mean with four server processes?
Flip to check your answerFold answer back
Answer. In Django’s default cache, local memory in each process until Chapter 57, so each process counts separately and four processes allow four times each rate.
Que. 4 Why is NUM_PROXIES set to 0?
Flip to check your answerFold answer back
Answer. With no proxy in front, REMOTE_ADDR is the client’s real address. DRF’s default, None, would use whatever X-Forwarded-For the client sends, so a script could escape the visitor limit by inventing addresses.
Que. 5 Which requests does the example client retry, and why not the others?
Flip to check your answerFold answer back
Answer. Reads, after a timeout, a 429, or a 502, 503, or 504, at most four tries in all. Writes are sent once, because without an idempotency key a retried POST could make a second draft.
Mini-Challenge
A program that filters the list must keep its filters as it follows next. Write a test, in api/tests/test_next_filters.py, showing that the next address of a filtered list still carries has_places=true.
Hint:save_events() from config.helpers saves as many published events as you ask for.
Model answer:
api/tests/test_next_filters.py
"""The next page keeps the filters (Chapter 51 challenge)."""
from datetime import timedelta
from django.test import TestCase
from django.utils import timezone
from rest_framework.test import APIClient
from config.helpers import save_events
class NextKeepsFiltersTests(TestCase):
"""Following next must not lose has_places."""
def test_next_carries_the_filter(self):
save_events(21, timezone.now() + timedelta(days=1))
page = APIClient().get('/api/v1/events/',
{'has_places': 'true'})
self.assertIn('has_places=true', page.json()['next'])
Terminal
uv run python manage.py test api.tests.test_next_filters
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
DRF builds next from the request’s own address, replacing only cursor, so every filter travels with it. The model answer was run and then removed; the chapter’s checkpoint does not include it.
What We Learned
Lists that grow need pages; a cursor keeps pages stable while rows change, at the cost of jumping.
A cursor’s ordering must end in something unique, such as id.
django-filter turns query parameters into form fields, so bad values become precise 422 problems.
In a query string + means a space; send an offset’s plus as %2B, or use Z.
Throttles count per caller in the cache; per process until a shared cache, and never a defence against attack.
NUM_PROXIES decides whose address a visitor has; leave it unset and clients choose their own.
Interactive documentation is a development tool, served from local files.
A good client sets timeouts, follows next, honours Retry-After, and retries only reads.
Key terms
Use Table 51.4 to explain this chapter’s ideas in your own words.
Table 51.4 — Key terms from Chapter 51
Term
Meaning
Pagination
Splitting a list into pages of a fixed size.
Offset paging
Skip n rows, then take a page.
Cursor
An opaque mark of where the last page ended.
Filter
A query parameter that narrows a list.
FilterSet
django-filter's declared set of filters.
Percent-encoding
Writing a character as %XX in an address.
Throttle
A limit on requests per caller per period.
Retry-After
Seconds to wait before trying again.
NUM_PROXIES
How many proxies' X-Forwarded-For to trust.
Swagger UI
A page that shows and tries an OpenAPI file.
MockTransport
httpx's stand-in server for tests.
Idempotent
Safe to repeat: the second time changes nothing.
Readiness checkpoint: you are ready for Chapter 52 when uv run python check.py ends with “all checks passed” and 734 tests, both lists answer with next, examples/otahque_client.py prints your events, and git log --oneline -1 shows this chapter’s commit.
Git Commit
Your Chapter 51 work was committed once, in Step 11, as “Page, filter, and limit the API; add docs”: the pagination, filter, and throttle modules, the settings, views, and addresses, the developers page and the shared copy template, the stylesheet and compiled CSS, the client, the contract, the OpenAPI file, pyproject.toml and uv.lock, and the three new test modules. If you kept the Mini-Challenge, commit it on its own:
Terminal
git add api/tests/test_next_filters.py
git commit -m "Check that next keeps the filters"
These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to limits across several processes and to what limits are for. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.
L1 (Junior): Why does an API page its lists?
What the interviewer is testing: Can you connect paging to cost, reliability, and the client’s work?
Flip to check your answerFold answer back
Perfect answer: A list that returns everything grows with the database: each answer gets slower, larger, and more likely to time out, and the client must hold all of it in memory. Paging fixes the size of each answer, twenty events in Otahque, and gives the client a next address for the rest, so the cost of one request stays the same however large the community grows. Filters go with it: a client asks only for what it needs, such as events with places next month, so most programs read one page.
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s
OK
Common mistakes:
Paging the HTML and forgetting the API, where programs ask far more often.
Letting clients ask for a page size of 10,000, which brings the problem back.
Follow-up the interviewer might ask:
How does a client know it has everything? (next is null.)
L2 (Mid-Level): Predict what offset paging does when an event is added
What the interviewer is testing: Can you reason about a list that changes between two requests?
Flip to check your answerFold answer back
Perfect answer: Offset paging asks for “skip two, take two”. If an event that sorts first is added after page 1 was read, every later event moves one place down, so skipping two now lands on the last event of page 1: it appears twice. A removal does the opposite and one event is never seen. A cursor asks for “after the last event I saw”, so the new event, which sorts before it, does not affect page 2 at all. The proof creates Proof 1 to 4, reads page 1 both ways, adds Proof 0, and reads page 2 both ways.
Figure 51.4 — Offset and cursor, as a row is added.
Behind the scenes:
Output
offset page 2 = rows 3 and 4 of the list now
cursor page 2 = rows after the last row seen
Code proof: both kinds of paging on the same events, made and rolled back:
l2_proof.py
"""Offset pages and cursor pages, as an event is added (L2)."""
from datetime import UTC, datetime, timedelta
from django.db import transaction
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
from api.pagination import EventCursor
from events.models import Event
START = datetime(2030, 1, 1, 18, tzinfo=UTC)
ask = APIRequestFactory(HTTP_HOST='localhost')
def make(n):
"""Save Proof n, starting n days after START."""
start = START + timedelta(days=n)
Event.objects.create(
title=f'Proof {n}', starts_at=start,
ends_at=start + timedelta(hours=1), timezone='UTC',
location='Online', capacity=5, status='published')
def titles(paginator, address):
"""Return the titles on the page address asks for."""
events = Event.objects.filter(title__startswith='Proof')
events = events.order_by('starts_at', 'id')
page = paginator.paginate_queryset(
events, Request(ask.get(address)))
return ', '.join(e.title for e in page)
with transaction.atomic():
for n in (1, 2, 3, 4):
make(n)
offset = LimitOffsetPagination()
cursor = EventCursor()
cursor.page_size = 2
print('offset page 1:', titles(offset, '/?limit=2'))
print('cursor page 1:', titles(cursor, '/'))
after = cursor.get_next_link()
make(0)
print('-- Proof 0 is added, sorting first --')
print('offset page 2:',
titles(offset, '/?limit=2&offset=2'))
print('cursor page 2:', titles(cursor, after))
transaction.set_rollback(True)
Testing paging on a list that never changes during the test.
Assuming the database returns rows in a stable order without order_by.
Follow-up the interviewer might ask:
Can a cursor miss an event? (One whose start time is edited to before the cursor, after the client passed it; that is why a sync stores the time of its last run, not a cursor.)
L3 (Senior): Defend cursor pagination for Otahque’s API
What the interviewer is testing: Can you weigh what a cursor gives against what it takes away?
Flip to check your answerFold answer back
Perfect answer: A cursor holds the position of the last row, not a page number. DRF’s encodes the start time of the last event on the page, as the proof decodes it, and the next query asks for events after it, using the index on starts_at. So pages never repeat or skip as events are published, and page 50 costs the same as page 1, because the database never counts past the skipped rows. What it takes away: no “page 7 of 12”, no total count, and no client-chosen size in DRF’s class; Otahque fixes twenty. For programs, which read in order, that is the right trade; for people browsing the site’s list, page numbers stay. The cursor is opaque to clients, so its format can change without breaking anyone who follows next.
Figure 51.5 — What a cursor gives, and takes.
Behind the scenes:
Output
cursor = base64("p=<starts_at of last row>")
next query: starts_at > p ORDER BY starts_at, id
Code proof: what a cursor holds, for events made and rolled back:
l3_proof.py
"""What a cursor holds (Chapter 51, L3)."""
from base64 import b64decode
from datetime import UTC, datetime, timedelta
from urllib.parse import parse_qs, urlsplit
from django.db import transaction
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
from api.pagination import EventCursor
from events.models import Event
START = datetime(2030, 1, 1, 18, tzinfo=UTC)
with transaction.atomic():
for n in (1, 2, 3):
start = START + timedelta(days=n)
Event.objects.create(
title=f'Proof {n}', starts_at=start,
ends_at=start + timedelta(hours=1),
timezone='UTC', location='Online', capacity=5,
status='published')
cursor = EventCursor()
cursor.page_size = 2
events = Event.objects.filter(title__startswith='Proof')
cursor.paginate_queryset(
events, Request(APIRequestFactory(
HTTP_HOST='localhost').get('/')))
link = cursor.get_next_link()
value = parse_qs(urlsplit(link).query)['cursor'][0]
print('next:', link.split('?')[0] + '?cursor=...')
print('inside:', b64decode(value).decode())
transaction.set_rollback(True)
Treating the cursor as a format clients may build.
Ordering by a column that repeats, without a unique tie-breaker.
Follow-up the interviewer might ask:
When would offset paging be right? (Small, slow-changing lists where people jump to a page, such as an admin’s list of members.)
L4 (Senior): The limit never triggers in production. Diagnose it
What the interviewer is testing: Can you find where state lives, and how many copies of it there are?
Flip to check your answerFold answer back
Perfect answer: A throttle counts in the cache. Otahque has not configured one, so it is LocMemCache, memory inside each server process. Production runs several processes, and a load balancer spreads requests between them, so each process sees a fraction of a script’s requests and none reaches 60. Every process is right by its own count. The fix is a cache all processes share, which Chapter 57 adds; until then, the rate per caller is in effect the rate times the number of processes, and the developers page should not promise more. I would also check NUM_PROXIES once a proxy is added, or every visitor will share the proxy’s address and the limit will trigger far too early.
Figure 51.6 — Diagnosing a limit that never triggers.
Behind the scenes:
Output
process A cache: visitor 127.0.0.1 -> 31 times
process B cache: visitor 127.0.0.1 -> 30 times
neither reaches 60; together they allow 120
Code proof: the cache that holds the counts, in one shell process:
l4_proof.py
"""Where throttle counts live (Chapter 51, L4)."""
from django.core.cache import caches
from django.test import Client
cache = caches['default']
print('cache:', type(cache).__name__)
visitor = Client(HTTP_HOST='localhost')
for _ in range(3):
visitor.get('/api/v1/events/')
times = cache.get('throttle_visitor_127.0.0.1', [])
print('this process counted:', len(times), 'of 60')
print('a second process would count from 0')
Output
cache: LocMemCache
this process counted: 3 of 60
a second process would count from 0
Common mistakes:
Testing limits with one process and assuming production behaves the same.
Raising the rate when it triggers too early behind a proxy, instead of setting NUM_PROXIES.
Follow-up the interviewer might ask:
What else in Otahque counts in the same cache? (allauth’s sign-in rate limits since Chapter 29, which have the same limitation until Chapter 57.)
L5 (Lead): “We have throttling, so we are safe from denial of service.” Respond
What the interviewer is testing: Can you place a control correctly in a defence, and say what it does not do?
Flip to check your answerFold answer back
Perfect answer: Throttling protects fairness, not availability under attack. It slows one caller who sends too much, a broken script or an over-eager agent, so it cannot crowd out others, and it tells that caller, with 429 and Retry-After, how to behave. It does not stop a flood: every refused request still reaches Django, runs authentication, and touches the cache, and an attacker with many addresses is many visitors. Floods are stopped before the application, by the proxy, the hosting network, or a service in front of it, which Chapter 63 discusses. So I would keep the throttles, label the rates as assumptions as Otahque does, measure real use before tightening them, and never describe them as a security control. DRF’s own documentation says the same.
Figure 51.7 — What a limit is for.
Behind the scenes:
Output
throttle fair use per caller, in Django
not it floods from many addresses
where proxy, network, provider (Chapter 63)
Code proof: the limits, per kind of caller:
Output
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s
OK
Common mistakes:
Setting rates from a guess and never revisiting them.
Counting a refused request as harmless: it still costs a trip through the stack.
Follow-up the interviewer might ask:
What would you measure before changing the rates? (Requests per caller per minute from the logs, by kind of caller, over a normal week.)
Next: Chapter 52, webhooks and reliable external integrations, tells partners when an event changes, instead of making them ask: signed messages, sent after the change commits, retried with care, and only to addresses that are safe to call.