Django Cache URL

3.4.6 · active · verified Thu Apr 16

This simple Django utility allows you to utilize the 12factor inspired CACHE_URL environment variable to configure your Django application. It supports various cache backends like locmem, db, file, memcached, and redis. The library is actively maintained, with a recent release on January 24, 2026.

Common errors

Warnings

Install

Imports

Quickstart

Configure your Django application's cache settings using the CACHE_URL environment variable, leveraging the `config` function. This example shows how to set up the default cache and a basic usage pattern.

import os
from django_cache_url import config

# Recommended: Set CACHE_URL in your environment, e.g., in .env file or deployment config
# Example: export CACHE_URL="redis://localhost:6379/1"
# Example: export CACHE_URL="memcached://127.0.0.1:11211"
# Example: export CACHE_URL="locmem://"

# In your Django settings.py:
CACHES = {
    'default': config(
        # Provide a default if CACHE_URL environment variable is not set
        default=os.environ.get('CACHE_URL', 'locmem://')
    )
}

# To parse an arbitrary URL string directly (not from env var):
# CACHES['custom_cache'] = parse('file:///tmp/django_cache')

# Example using the cache (e.g., in a view or management command)
from django.core.cache import cache

def my_cached_function():
    data = cache.get('my_key')
    if data is None:
        data = "Expensive calculation result!"
        cache.set('my_key', data, 60*5) # Cache for 5 minutes
    return data

print(f"Cache configured for backend: {CACHES['default']['BACKEND']}")
print(f"Retrieved data: {my_cached_function()}")

view raw JSON →