django缓存
2019-02-01 本文已影响0人
鲸随浪起
django-redis官网文档:
http://django-redis-chs.readthedocs.io/zh_CN/latest/
redis.py文档
https://redis-py.readthedocs.io/en/latest/
#Django的缓存配置
#caches缓存,
CACHES={
"default":{
"BACKEND":"django_redis.cache.RedisCache",
"LOCATION":"redis://127.0.0.1:6379/9",
"OPTIONS":{
"CLIENT_CLASS":"django_redis.client.DefaultClient",
}
}
}
#下面是把用户登录的session存储在redis中
#配置session存储
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
缓存设置
from django.core.cache import cache #缓存
设置缓存:cache.set("yzm",rand_str,20)#键,值,时间
读缓存:cache.get("yzm")#键
redis操作
浏览记录.jpg#浏览记录
from django_redis import get_redis_connection #redis数据库
conn = get_redis_connection("default")
history_key = "history_%d"%user.id
#移除列表中的goods_id
conn.lrem(history_key,0,goods_id)
#把goods_id插入列表的左侧
conn.lpush(history_key,goods_id)
#只保存用户最新浏览的5条信息
conn.ltrim(history_key,0,4)
购物车jpg
购物车
conn = get_redis_connection('default')
cart_key = "cart_%d" %user.id
#先尝试获取sku_id的值,使用hget cart_key属性
#如果sku_id在hash中不存在,hget返回None,hget 键 属性
cart_count = conn.hget(cart_key,sku_id)
=================================================
conn = get_redis_connection("default")
cart_key = "cart_%d"%user.id
#hgetall:{"商品id":"商品数量"}
cart_dict = conn.hgetall(cart_key)
#redis更新
conn.hset(cart_key,sku_id,count)
vals = conn.hvals(cart_key) #hvals返回所有的值
#删除
conn.hdel(cart_key,sku_id)
#获取长度
cart_count = conn.hlen(cart_key)
=================================================
···