python
40 lines · 8 steps
A login rate throttle in Django REST Framework
Limits login attempts per username-plus-IP and locks the pair out once the limit is hit.
Explained by
highlit
1from django.core.cache import cache
2from rest_framework.throttling import SimpleRateThrottle
3
4
5class LoginRateThrottle(SimpleRateThrottle):
6 scope = "login"
7
8 def get_cache_key(self, request, view):
9 username = (request.data.get("username") or "").strip().lower()
10 if not username:
11 return None
12 ident = self.get_ident(request)
13 return self.cache_format % {
14 "scope": self.scope,
15 "ident": f"{username}:{ident}",
16 }
17
18 def allow_request(self, request, view):
19 self.key = self.get_cache_key(request, view)
20 if self.key is None:
21 return True
22
23 if cache.get(f"{self.key}:locked"):
24 self.wait_time = cache.ttl(f"{self.key}:locked") or self.duration
25 return False
26
27 self.history = self.cache.get(self.key, [])
28 self.now = self.timer()
29 while self.history and self.history[-1] <= self.now - self.duration:
30 self.history.pop()
31
32 if len(self.history) >= self.num_requests:
33 cache.set(f"{self.key}:locked", True, timeout=self.duration)
34 self.wait_time = self.duration
35 return False
36
37 return self.throttle_success()
38
39 def wait(self):
40 return getattr(self, "wait_time", None) or super().wait()
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Keying a throttle on username-plus-IP targets brute-force attempts without blocking whole networks.
- 2A short-lived lock flag in the cache turns a soft rate limit into a hard cooldown once tripped.
- 3Returning None from the cache key cleanly opts a request out of throttling entirely.
Related explainers
python
import datetime from dataclasses import dataclass
Parsing fixed-width records in Python
parsing
generators
dataclasses
Intermediate
8 steps
python
from itertools import product from dataclasses import dataclass from decimal import Decimal
Generating product variants with itertools.product
cartesian-product
dataclass
decimal
Intermediate
7 steps
python
from typing import Callable, Dict, Type class PluginRegistry:
A decorator-based plugin registry in Python
decorators
registry pattern
factory
Intermediate
9 steps
ruby
namespace :counter_cache do desc "Recalculate comments_count for posts after a backfill" task warm_post_comments: :environment do scope = Post.where(comments_count: nil).or(Post.where("comments_count < 0"))
Backfilling counter caches in a Rake task in Rails
counter-cache
batching
rake-tasks
Intermediate
6 steps
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 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/a-login-rate-throttle-in-django-rest-framework-explained-python-ec0c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.