- 本地安装Redis数据库
- Django环境中
pin install django-redis
在settings文件中设置Redis数据库作为Django的缓存。
# 配置Redis为Django缓存
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
# 将session缓存在Redis中
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
1.使用
from django.core.cache import cache
def home(request):
# 尝试从Redis中获取缓存,如果没有,设置缓存
context = cache.get('index_page_cache')
if context is None:
print('没有缓存')
context = {
'types': 'types',
'banners': 'banners',
'promotion':'promotion',
}
# 设置缓存
cache.set('index_page_cache', context)