Skip to main content

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.
pip install redis
pip freeze > requirements.txt

Settings

You need to add the caches settings to settings.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.
CACHES = { 
    "default": {
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": env('REDIS_URL'),
    }
}
On the Sevalla dashboard, you can create and connect a Redis database to your Django app. After creating the Redis instance, go to Networking and then click Add internal connection, select the Redis instance you created, and then add the REDIS_URL environment variable to the application.

Example

To use the cache on a view, you can import the cache_page function and decorate some of your view functions or classes. Here is an example:
  1. Create an app that allows you to add a new view.
    python manage.py startapp app
    
  2. Create a view function and decorate it with cache_page. This example will cache the view for two minutes.
    # app/views.py
    from django.http import HttpResponse 
    from django.utils import timezone
    from django.views.decorators.cache import cache_page
    
    @cache_page(60 * 2)
    def cached_view(request):
        return HttpResponse(f"Cached at {timezone.now()} for two minutes")
    
    # example/urls.py
    from django.contrib import admin
    from django.urls import path
    
    from app.views import cached_view 
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('cached/', cached_view, name='cached_view'), 
    ]
    
  3. Navigate to the cached/ endpoint, the time the view was added to the cache will be displayed until the cache is updated.
The settings for 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. The cf-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 with never_cache.
from django.views.decorators.cache import never_cache

@never_cache
def login(request):
    ...
By default, all admin views in Django use the 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.
from django.views.decorators.cache import cache_control

@cache_control(max_age=60*60*24)
def page(request):
   ...
To verify your pages are being cached correctly, request a page and inspect the response headers. The 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.