1.安装django依赖包 pip install djange-redis==4.8.0
2.配置文件settings 需要开启redis服务 sudo service redis start,否则连接被拒
# 缓存配置 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", # or 127.0.0.1 "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } }
3.1页面缓存
view:
class CachePage(View): """ 缓存页面 """ def get(self, request): print "只打印一次则使用缓存" return render(request, "logok.html")
通过配置url调用缓存
from django.views.decorators.cache import cache_page
urlpatterns = [ url(r'auth_cache_page/$', cache_page(60)(views.CachePage.as_view()), name='auth_cache_page'), ] # 设置过期时间60s 注意格式 执行到cache_page,有缓存则不执行view,直接调用缓存
时间单位为秒, 60*60*24*7 一周时间
3.2访问缓存
view:
from django.core.cache import cache
class CacheVisit(View): """ 访问数据库缓存 from django.core.cache import cache """ def get(self, request): users = cache.get("users") # 没users则返回None if not users: users = User.objects.all() cache.set("users", users, 60) # 设置缓存key及过期时间
# cache.add("users", users, 60) # 更新缓存或相当于set
# cache.set_many({"a": 1, "b": 3}) # 设置多个缓存
# cache.get_or_set("a", "默认值", 60) # 存在key a则获取a的值,不存在则设置key a,值为默认值
# cache.delete("a") # 删除
# cache.delete_many(["a", "b"]) # 删除多个缓存
# cache.clear() # 清除所有缓存
print "只打印一次则使用缓存" return render(request, "users.html", locals())
html
<body> {% for user in users %} {{ user.username }}<br> {% endfor %} </body>