Cache framework using Redis
Django’s cache framework can be used with a Django app deployed on Sevalla by connecting a Redis service to your Django app. To enable the cache framework, Redis needs to be installed and your settings updated.Install
The Python Redis library must be a dependency so that Django can connect to your Redis instance.Settings
You need to add the caches settings tosettings.py.
Reference the RedisCache backend that is included with Django. Use your preferred method for defining configuration values for LOCATION, which is the URL of your Redis instance. django-environ is used for this example.
REDIS_URL environment variable to the application.
Example
To use the cache on a view, you can import thecache_page function and decorate some of your view functions or classes. Here is an example:
-
Create an app that allows you to add a new view.
-
Create a view function and decorate it with
cache_page. This example will cache the view for two minutes. -
Navigate to the
cached/endpoint, the time the view was added to the cache will be displayed until the cache is updated.
RedisCache used here will also work with template fragment caching and direct use of the cache API.
If you want to cache your entire site, consider using edge caching instead.
CDN
If you are using WhiteNoise to serve your static files, you can enable the CDN setting to cache your static assets on Cloudflare. To verify your static files are being cached correctly, request a file and inspect the response headers. Thecf-cache-status header should be either HIT or MISS. MISS should only occur when the file needs to be set or updated in the CDN. HIT will be the expected value for most requests.
Edge Caching
If your application primarily serves pages that don’t change frequently, you can use edge caching to store and serve pre-rendered responses. This caching applies across the entire application, and only endpoints that explicitly disable caching via response headers will be excluded, resulting in faster load times and reduced server load. You can prevent caching by decorating a view withnever_cache.
never_cache decorator.
To control how long a page will remain in the cache, you need to set the max-age response headers. One way to do that is to use the cache_control decorator.
cf-cache-status header should be either HIT or MISS. MISS should only occur when the page needs to be set or updated in the CDN. HIT will be the expected value for most requests.