django-stash
Remember a value for the rest of the current request, and read it back from anywhere — without passing request around.
import stash
def get_current_tenant():
return stash.get_or_set("tenant", lambda: Tenant.objects.get(pk=...))
Call it ten times in one request: the loader runs once. Next request: it runs again.
This is not a cache backend. Nothing is shared between requests, processes, or workers. Values live only while a request is being handled, and are thrown away when it finishes.
Install
pip install django-stash
MIDDLEWARE = [
"stash.middleware.StashMiddleware",
# ...
]
No INSTALLED_APPS entry needed.
The problem it solves
You have something that is expensive to compute, and needed in several unrelated places during one request — a template tag, a model method, a serializer, a signal handler:
# views.py
settings = SiteSettings.objects.get()
# templatetags/theme.py
settings = SiteSettings.objects.get() # same query again
# models.py
settings = SiteSettings.objects.get() # and again
The usual fixes are awkward: thread request through every function, hang attributes off request, or reach for a global cache and then worry about invalidation.
With stash, each call site asks for the value by name and the first one pays:
import stash
def get_site_settings():
return stash.get_or_set("site_settings", lambda: SiteSettings.objects.get())
Where this fits
Reach for stash when a value is expensive, needed in more than one place during a single request, and awkward to get to from where you are:
- A request-derived value needed somewhere without
request. Middleware resolves the current tenant from the hostname; a model manager, a permission check, and a signal handler all need it too, but none of them haverequestin scope.def get_current_tenant(): return stash.get_or_set("tenant", resolve_tenant_from_request)
- A check that fans out across a page. A changelist renders 50 rows and calls
can_edit(obj)for each. Ifcan_editstarts with something request-wide — "is this user a reviewer this month" — that shouldn't be recomputed 50 times. - You're about to write
request._cached_thing = .... This pattern already exists in most Django codebases: stash something onrequestin middleware, read it back everywhere else. It works, but it only works whererequestis reachable, and it leaks the caching detail into every call site.stash.get_or_setis the same idea, usable from anywhere, without arequestreference. - A value that must be refreshed mid-request after a write. Read settings early; a view updates them; later code in the same request must see the new value. One
stash.clear("site_settings")call after the write handles it — seeclearbelow. - Batch scripts, one memo per unit of work. Wrap each row/item in
stash_scope()so lookups inside it are cheap, and nothing survives to the next item.
Where this doesn't fit
- You want the answer shared across requests, workers, or deploys. That's Django's cache framework (
django.core.cache, backed by Redis/Memcached/the DB). Stash never outlives one scope — put it in front of that cache as L1 if you want both. - The value needs to reach other processes. Stash is per-process, per-scope. One worker's stash tells another worker nothing.
- A pure function with no invalidation need, no request in the picture.
functools.lru_cacheis simpler and doesn't need a scope at all.
Alternatives
| Scope | Needs request? |
Cost per hit | Crosses requests / processes? | Invalidation | |
|---|---|---|---|---|---|
| stash | One request, or a stash_scope() block |
No | Dict lookup | Never | Automatic when the scope ends; clear() any time before that |
django-request-cache |
One request | Yes — exposes the whole request globally to get one | Attribute lookup | No | Automatic at request end only |
request._cached_x (manual) |
One request | Yes, at every call site | Attribute lookup | No | Manual, ad hoc |
| Django's cache framework | Until TTL, eviction, or delete | No | locmem: lock + dict. Redis/Memcached/DB: network round trip + (de)serialization, every call | Yes — that's the point | TTL, cache.delete(), or signals |
functools.lru_cache |
Process lifetime | No | Dict lookup | Accidentally, forever — same answer until the process restarts | None, short of calling cache_clear() yourself |
| Bare thread-local / module global | However long you remember to keep it valid | No | Dict/attribute lookup | Accidentally — sync workers reuse a thread across requests | Whatever you remember to write, wherever you remember to write it |
The last row is the trap: a hand-rolled threading.local() or asgiref.Local() looks identical to stash until a worker process reuses its thread for a second request and the old value is still sitting there. Stash's storage is the same mechanism (asgiref.local.Local), but the lifetime is never left to memory — StashMiddleware opens and closes the scope on every single request, so there's no window where a stale value can survive into the next one.
django-request-cache takes the same idea a step further: instead of exposing one named value, it makes the whole request object reachable from anywhere first (via django-userforeignkey's get_current_request()), then hangs a cache off it as an attribute. That's an extra dependency, and a much bigger object made globally available than most call sites need. Stash's storage never holds request — only the specific values you chose to stash, by name.
Django's cache framework (django.core.cache) is still the right choice the moment a value needs to survive past one request — nothing here replaces it. The trade-off in the table above is the one to remember: reach for the cache framework when a value is shared across requests or processes, and put stash in front of it when the same value is read more than once inside a single request.
Usage
get_or_set
import stash
def get_feature_flags():
return stash.get_or_set("feature_flags", load_feature_flags_from_db)
- First call in a request: runs
load_feature_flags_from_db(), stores the result, returns it. - Later calls in the same request: returns the stored result. The loader is not called.
- After the request ends: the stored value is gone.
memoize
Same thing, as a decorator:
import stash
@stash.memoize
def get_exchange_rate(currency):
return ExchangeRate.objects.get(currency=currency).rate
get_exchange_rate("EUR") and get_exchange_rate("USD") are remembered separately (the key is built from the arguments). Use @stash.memoize(key="...") for a fixed key that ignores arguments.
get, set, clear
stash.set("user_permissions", perms)
stash.get("user_permissions") # -> perms, or None
stash.get("missing", default=[]) # -> []
stash.clear("user_permissions") # forget one value
stash.clear() # forget everything for this request
clear is what you call after writing to the underlying data, so later reads in the same request see the new state:
def update_site_settings(**changes):
SiteSettings.objects.filter(pk=1).update(**changes)
stash.clear("site_settings")
Outside a request
Nothing is stored unless a scope is open. In a management command, Celery task, or shell:
stash.get_or_set("k", loader) # just calls loader() every time
stash.set("k", value) # does nothing
stash.get("k") # -> None
That is deliberate: a long-lived worker never accumulates stale values by accident.
If you want the same per-unit-of-work behaviour there, open a scope yourself:
with stash.stash_scope():
process_batch() # values remembered for this block only
Behaviour in one table
| Situation | get_or_set("k", loader) |
|---|---|
| Inside a request, first call | runs loader(), stores, returns |
| Inside a request, later call | returns stored value |
After stash.clear("k") |
runs loader() again |
| Different request | runs loader() again |
| Different thread / process | runs loader() again |
| No middleware / no scope | runs loader() every time; stores nothing |
Notes
- Values are stored and returned as shallow copies. Mutating what you get back does not change what is stored. Don't rely on identity.
- Stash is an L1 in front of whatever you already do. If you also want cross-process sharing, keep using Django's cache as L2 inside your loader.
- Works under WSGI and ASGI, with sync or async views. The middleware is sync- and async-capable, so it does not force Django to adapt the rest of the chain. Storage is
asgiref.local.Local.
Development
cd django-stash
python -m venv .venv && source .venv/bin/activate
pip install -e ".[testing,development]"
python testmanage.py test
Metadata
Release files for django-stash 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| django_stash-0.2.0.tar.gz | 8.0 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| django_stash-0.2.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 16.8 kB
Release files / django_stash-0.2.0.tar.gz
| Download URL | django_stash-0.2.0.tar.gz |
|---|---|
| Size | 8.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
47b43405b3ede42e7e598d80066d4aad155e75bfeba73eae5212e0e27a58a123
|
|
BLAKE2b-256 checksum How to use checksums |
90c042642d1ee32480619066161394f6aa173463980d31a6e768847295c0d200
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 12, 2026.
Transparency logRelease files / django_stash-0.2.0-py3-none-any.whl
| Download URL | django_stash-0.2.0-py3-none-any.whl |
|---|---|
| Size | 8.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6b24c8c1a7e1d01c0d30e80242ef5eed9e4db786d8b71f37a544d332aa34654f
|
|
BLAKE2b-256 checksum How to use checksums |
8375c0a06aa638a6a22d026952b4cd11cbace6e49af9bf3a885119f7bc87d28b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 12, 2026.
Transparency log