← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Caching Strategies

Topic: Performance

Advertisement

Introduction

Implement caching to improve application performance and reduce database load.

Function Caching

from functools import lru_cache
from datetime import timedelta

@lru_cache(maxsize=128)
def expensive_computation(n):
    return n ** 2

# With TTL (time-to-live)
from functools import wraps
import time

def cache_with_ttl(ttl_seconds):
    def decorator(func):
        cache = {}
        @wraps(func)
        def wrapper(*args):
            now = time.time()
            if args in cache:
                value, timestamp = cache[args]
                if now - timestamp < ttl_seconds:
                    return value
            result = func(*args)
            cache[args] = (result, now)
            return result
        return wrapper
    return decorator

Django Caching

# settings.py
CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
    }
}

# Views
from django.views.decorators.cache import cache_page

@cache_page(60 * 15)  # 15 minutes
def my_view(request):
    pass

Practice Problems

  1. Implement function memoization
  2. Use Redis for application caching
  3. Cache database queries
  4. Implement cache invalidation
  5. Create cache decorator with TTL

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →