python
50 lines · 2 tabs
Priya Sharma
Jan 2026
2 tabs
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'PASSWORD': 'your-redis-password',
'SOCKET_CONNECT_TIMEOUT': 5,
'SOCKET_TIMEOUT': 5,
'CONNECTION_POOL_KWARGS': {'max_connections': 50}
},
'KEY_PREFIX': 'myapp',
'VERSION': 1,
}
}
# Use Redis for sessions
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
from django.core.cache import cache
from django.views.decorators.cache import cache_page
def get_popular_products():
"""Cache expensive query."""
cache_key = 'popular_products'
products = cache.get(cache_key)
if products is None:
from products.models import Product
products = list(Product.objects.filter(
featured=True
).order_by('-sales')[:10])
cache.set(cache_key, products, 3600) # Cache for 1 hour
return products
# Cache view for 15 minutes
@cache_page(60 * 15)
def product_list(request):
# View implementation
pass
# Invalidate cache
def clear_product_cache():
cache.delete('popular_products')
cache.delete_pattern('product:*') # Delete by pattern
2 files · python
Explain with highlit
Redis provides fast in-memory caching for Django. I configure it as cache backend and use for session storage. I cache expensive querysets, computed values, and API responses. The cache.get_or_set() method simplifies cache-aside pattern. For cache invalidation, I use versioning or targeted deletes. I set appropriate TTLs based on data volatility. Redis also enables rate limiting, message queues, and pub/sub. For distributed systems, Redis centralizes cache across servers. This dramatically improves response times for read-heavy workloads.
Related snips
python
import os
import stat
for root, _dirs, files in os.walk('/etc'):
for name in files:
path = os.path.join(root, name)
Python security audit script for exposed risky filesystem state
python
auditing
host-security
by Kai Nakamura
1 tab
ruby
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
rails
caching
http-caching
by Alex Kumar
1 tab
python
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
cost = models.DecimalField(max_digits=10, decimal_places=2)
margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)
Django model signals vs overriding save
django
python
models
by Priya Sharma
2 tabs
python
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
Django URL namespacing and reverse lookups
django
python
urls
by Priya Sharma
3 tabs
ruby
json.array! @posts do |post|
json.cache! ['v1', post], expires_in: 1.hour do
json.id post.id
json.title post.title
json.excerpt post.excerpt
json.published_at post.published_at
Fragment caching for expensive JSON serialization
rails
caching
performance
by Alex Kumar
1 tab
typescript
import { randomBytes, createHash } from "crypto";
import jwt from "jsonwebtoken";
import { RefreshTokenStore } from "./store";
const ACCESS_SECRET = process.env.ACCESS_SECRET!;
const ACCESS_TTL = "15m";
JWT access + refresh token rotation (conceptual)
security
node
jwt
by codesnips
3 tabs
Share this code
Here's the card — post it anywhere.