django-redis缓存

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>

 

posted on 2018-05-23 02:08 .Tang 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/tangpg/p/9075019.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值