0
0
Djangoframework~5 mins

Cache framework configuration in Django

Choose your learning style9 modes available
Introduction

Cache helps your website load faster by saving data temporarily. Configuring cache means telling Django how and where to save this data.

You want to speed up your website by storing frequently used data.
You have a slow database query and want to avoid running it every time.
You want to reduce server load by reusing stored responses.
You want to cache whole pages or parts of pages for faster delivery.
Syntax
Django
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
    }
}

BACKEND tells Django which cache system to use.

LOCATION is where the cache data is stored; it depends on the backend.

Examples
This example uses Memcached, a fast external cache server running locally.
Django
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}
This example stores cache data in files on your server.
Django
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/var/tmp/django_cache',
    }
}
This example uses Redis, a popular fast cache server.
Django
CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/1',
    }
}
Sample Program

This code saves a greeting message in the cache for 30 seconds, then retrieves and prints it.

Django
from django.core.cache import cache

# Save a value in cache for 30 seconds
cache.set('greeting', 'Hello, friend!', 30)

# Retrieve the cached value
message = cache.get('greeting', 'No greeting found')

print(message)
OutputSuccess
Important Notes

Remember to choose a cache backend that fits your project size and hosting environment.

Local memory cache is simple but only works per process and is not shared across servers.

External caches like Memcached or Redis work well for bigger or multi-server projects.

Summary

Cache configuration tells Django how to store temporary data to speed up your site.

You set the cache backend and location in the CACHES setting.

Use cache to save time and reduce repeated work on your server.