caching
Sometimes a view does a bunch of work just to return the same thing it returned a few seconds ago. Caching lets you skip that work for a little while. Add @app.cache to a public view, and Spiderweb can reuse its response instead of calling the view again.
This is opt-in -- creating a cache backend doesn't automatically cache all your routes.
getting started
from spiderweb import SpiderwebRouter
from spiderweb.response import HttpResponse
app = SpiderwebRouter()
@app.route("/")
@app.cache
def index(request):
return HttpResponse("HELLO, WORLD!")
When using the @app.cache decorator, Spiderweb defaults to an InMemoryCache with a time-to-live (TTL) of 60 seconds. (@app.cache() works too.) To change the settings for a particular view, pass them to the decorator:
@app.route("/news")
@app.cache(ttl=120, max_size=100)
def news(request):
return HttpResponse("Nothing to report. The spiders are doing fine.")
Warning
Decorator order matters! Put @app.route(...) above @app.cache, so the router registers the cached version of your view. Putting them the other way around registers the original view and skips the cache.
The same rule applies to a route group:
from spiderweb import RouteGroup
api = RouteGroup(prefix="/api")
@api.route("/status")
@app.cache(ttl=30)
def status(request):
return {"status": "all good"}
app.include_routegroup(api)
what gets cached?
Only successful 200 responses to GET and HEAD requests without a request body are cached. GET and HEAD have separate cache entries. The decorator doesn't change which methods a route accepts; if you want HEAD support, include it in the route's allowed_methods:
@app.route("/status", allowed_methods=["GET", "HEAD"])
@app.cache()
def status(request):
return HttpResponse("All good!")
POST, PUT, PATCH, DELETE, and other methods always run the view when they reach it. Exceptions and non-200 responses are never cached.
All of the built-in response types are supported: HttpResponse, JsonResponse, RedirectResponse, TemplateResponse, and FileResponse. The status rule still applies, so a normal redirect response is not cached.
For a FileResponse, the cached response stores the file path, not the file's bytes. Spiderweb reads the file again on each hit, so caching the view doesn't avoid disk reads.
Custom response subclasses and data that can't be safely serialized bypass caching. Spiderweb does not use pickle to store responses. Each cache hit creates a fresh response object, rather than handing out the same mutable object to multiple requests.
keep it public
Caching is for public, read-only views. Don't decorate views that change data, mutate a session, or perform any other side effect that needs to happen on every request. A cache hit skips the view entirely!
There is no cache stampede suppression -- simultaneous misses for the same key can run the view more than once. Don't use caching as a guarantee that work happens only once.
Spiderweb takes a conservative approach to personal data. It bypasses the cache for:
- Requests with a
CookieorAuthorizationheader. - Authenticated requests or requests with a nonempty session.
- Requests authenticated by a trusted server, with
REMOTE_USERorAUTH_TYPEset in the request environment. - Requests or responses with
Cache-Control: private,no-store, orno-cache. - Requests with
Pragma: no-cache. - Responses that set cookies, or have
Vary: *.
These checks aren't a substitute for choosing safe views. For example, a view that increments a counter in request.SESSION is not a good caching candidate, even if the session starts out empty. See the sessions documentation for views that should run on every visit.
how requests are kept apart
A cache key includes the view's identity, HTTP method, scheme, host, path, raw query string, URL arguments, script prefix (SCRIPT_NAME), client address (REMOTE_ADDR), and all incoming HTTP headers from request.headers and the HTTP environment. This deliberately keeps different clients, mount points, and header values apart, including headers named by a response's Vary header. It's safer, but means fewer hits if your clients send frequently changing headers.
Query strings aren't normalized. /search?a=1&b=2 and /search?b=2&a=1 can have separate entries, even if your view treats them as the same request.
middleware still runs
Caching skips the view, not the middleware. Request middleware still runs, and response middleware and post-processing run again for each request, including cache hits.
Spiderweb takes a snapshot of the response before response middleware changes it, and only stores that snapshot after rendering succeeds and the final response passes the cache eligibility checks. Middleware-generated cookies, CSRF values, and gzip output aren't stored and shared between requests. A response that becomes private, sets a cookie, or stops being a 200 during response processing isn't stored.
templates are a bit different
For a TemplateResponse, Spiderweb caches the template definition and the view-provided context, not the final rendered page. On a hit, it creates a new template response with the current request and renders again. Request-specific and middleware-provided template context stays fresh.
from spiderweb.response import TemplateResponse
@app.route("/greeting")
@app.cache(ttl=120)
def greeting(request):
return TemplateResponse(
request,
template_string="Hello, {{ greeting }}!",
context={"greeting": "spider enthusiast"},
)
The view context must be JSON-serializable without changing its types or dictionary keys when loaded again. Use strings, finite numbers, booleans, None, lists, and dictionaries with string keys, including for nested values. Tuples and dictionaries with integer keys bypass caching, even though Python's JSON encoder normally accepts them, because loading them would produce lists or string keys. Live database objects and arbitrary Python objects also bypass caching instead of being pickled. The view-provided context can remain stale until the entry expires, even though the template is rendered again.
ttl and size limits
TTL values are in seconds and must be finite, nonnegative numbers. A TTL of 0 disables storage. Spiderweb chooses the TTL in this order:
- The
ttlpassed to@app.cache(...). - The router's
cache_ttl, if configured. - The backend's
ttl, which defaults to60.
from spiderweb import SpiderwebRouter
from spiderweb.cache import InMemoryCache
app = SpiderwebRouter(
cache=InMemoryCache(ttl=60, max_size=100),
cache_ttl=90,
)
@app.route("/news")
@app.cache(ttl=120)
def news(request):
return {"headline": "Spiders remain small"}
Here, decorated views use 90 seconds unless they override it, and news uses 120 seconds.
max_size is an entry count, not a byte limit. It must be a positive integer or None for no configured limit. For the memory, file, and database backends, it caps the whole backend, not just one view. A decorator's max_size override applies when that route writes an entry, so it can evict entries written by other routes too.
InMemoryCacheevicts the least recently used entry (LRU).FileCacheandDatabaseCacheevict the oldest-written entries.- Expired entries are cleaned up lazily during cache operations, not by a background worker.
- Redis and Memcached manage their own eviction. Their backends reject
max_size, including a decorator override; configure limits in the external service instead.
Note
Updating your application's data doesn't automatically invalidate cached responses. A cached view's data can stay stale until its TTL expires or you clear the cache. This is server-side caching, not browser or CDN cache control; configure HTTP caching headers separately if you need those too.
choosing a backend
All backends live in spiderweb.cache. Pass an instance as the router's cache argument; the configured instance is available as app.cache_backend.
in-memory cache
from spiderweb import SpiderwebRouter
from spiderweb.cache import InMemoryCache
app = SpiderwebRouter(cache=InMemoryCache(ttl=60, max_size=100))
InMemoryCache(ttl=60, max_size=None) needs no extra dependencies and is the default. Entries live in this router's process and disappear when it stops. Separate routers and separate server workers don't share their default in-memory caches.
For multiple workers that need to share entries, choose a shared file location, the same database, Redis, or Memcached instead.
file cache
from spiderweb import SpiderwebRouter
from spiderweb.cache import FileCache
app = SpiderwebRouter(cache=FileCache(path="/var/tmp/myapp-cache", ttl=60, max_size=100))
The constructor is FileCache(ttl=60, max_size=None, path=None). Use path= when choosing a directory to keep things clear. It stores entries on disk and survives server restarts. If you don't pass a path, it uses a .spidercache directory in the current working directory. Workers must use the same directory to share entries.
Entries use JSON with base64-encoded byte values, and disk writes are atomic. Choose a location that your application can read and write, and keep it out of your publicly served files.
database cache
from spiderweb import SpiderwebRouter
from spiderweb.cache import DatabaseCache
app = SpiderwebRouter(
db="myapp.sqlite",
cache=DatabaseCache(ttl=60, max_size=100),
)
DatabaseCache(ttl=60, max_size=None) uses the router's existing app.db_session_factory. Spiderweb automatically creates a spiderweb_cache_entries table for the entries. There isn't a separate database argument on this backend -- configure the router's db instead.
Entries persist across restarts and can be shared by processes using the same database. See databases for the supported connection options.
redis cache
Install the optional client dependency:
uv add 'spiderweb-framework[redis]'
Then point the backend at a running Redis server:
from spiderweb import SpiderwebRouter
from spiderweb.cache import RedisCache
app = SpiderwebRouter(
cache=RedisCache(ttl=60, host="localhost", port=6379, db=0),
)
The constructor is RedisCache(ttl=60, host="localhost", port=6379, db=0, **kwargs). Extra keyword arguments are passed to the Redis client for connection settings, such as credentials and timeouts. Installing the extra gives you the Python client, not a Redis server.
memcached cache
Install the optional client dependency:
uv add 'spiderweb-framework[memcached]'
This backend uses pylibmc, which may require native libmemcached development libraries on your system. You'll also need a running Memcached server:
from spiderweb import SpiderwebRouter
from spiderweb.cache import MemcachedCache
app = SpiderwebRouter(
cache=MemcachedCache(ttl=60, servers=["127.0.0.1"]),
)
The constructor is MemcachedCache(ttl=60, servers=None, **kwargs). The default server list is ["127.0.0.1"], and extra keyword arguments go to the pylibmc client. As with Redis, installing the extra doesn't install or start the service.
Optional dependencies are loaded only when their backend is selected. You don't need to install Redis or Memcached extras to use the memory, file, or database backends.
using the storage directly
Need to store a small piece of data rather than a whole response? The backend has a bytes-based API:
app.cache_backend.set("weather:summary", b"Sunny, with a chance of spiders.", ttl=30)
summary = app.cache_backend.get("weather:summary")
app.cache_backend.delete("weather:summary")
app.cache_backend.clear()
get(key)returnsbytes, orNonefor a missing or expired entry.set(key, value, ttl=None, max_size=None)stores a byte value. With no TTL override, it uses the backend's TTL, not the router'scache_ttl.delete(key)removes an entry.clear()invalidates this backend's cache entries. It doesn't flush unrelated keys from a shared Redis or Memcached service.
Backends that share storage also share the scope of clear(). For example, two routers using the same file directory or database table can invalidate each other's entries. Redis removes only Spiderweb's namespaced, hashed cache keys in the selected database. Memcached rotates a shared Spiderweb generation, making old entries inaccessible until they expire naturally or the service evicts them; it doesn't flush the service. Use separate storage if different apps need independent caches.
Use your own distinct keys for application data. The response decorator generates its own keys; this API doesn't provide a URL-based invalidation helper. To invalidate all cached views in the backend, call app.cache_backend.clear().
Backend failures during decorated requests are logged and fail open, so a cache outage doesn't stop the original view from running. Direct storage calls don't swallow those failures -- handle exceptions yourself when using app.cache_backend.
sync and async views
The decorator supports function views only; don't apply @app.cache directly to a class-based view. Both def and async def functions work under WSGI and ASGI:
@app.route("/async-status")
@app.cache(ttl=30)
async def async_status(request):
return {"status": "still good"}
For async views, blocking backend I/O is run with asyncio.to_thread rather than blocking the event loop. The direct storage API is synchronous, so move your own direct backend calls off the event loop if you use them inside async code.