1.下载安装django-redis
pip install django-redis
2.settings.dev中添加配置
# 设置redis缓存 CACHES = { # 默认缓存 "default": { "BACKEND": "django_redis.cache.RedisCache", # 项目上线时,需要调整这里的路径 "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, # 提供给xadmin或者admin的session存储 "session": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, # 提供存储短信验证码 "sms_code":{ "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } # 设置xadmin用户登录时,登录信息session保存到redis SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "session"
3.使用redis
from django_redis import get_redis_connection // 链接redis数据库 redis_conn = get_redis_connection("default")
redis_sms = redis_conn.get("sms_%s" % mobile) #从redis中获取数据,或者删除数据等操作
# 3. 保存短信验证码到redis ,将数据保存到redis中
redis_conn.setex("sms_%s" % mobile, constants.SMS_EXPIRE_TIME, sms_code)
redis_conn.setex("mobile_%s" % mobile, constants.SMS_INTERVAL_TIME,"_")
redis_sms = redis_conn.get("sms_%s" % mobile) #从redis中获取数据,或者删除数据等操作
#删除redis里面的相应数据
redis_conn = get_redis_connection("sms_code")
pipe = redis_conn.pipeline()
pipe.multi()
pipe.delete("send_%s" % mobile)
pipe.delete("sms_%s" % mobile)
pipe.execute()
实现增删查的作用
4.redis取数据
# 把商品信息保存到redis中 redis_conn = get_redis_connection("cart") pipe = redis_conn.pipeline() pipe.multi() pipe.hset("cart_%s" % user_id, course_id, expire_time) pipe.sadd("selected_%s" % user_id, course_id) # 默认用户添加商品到购物车时就是默认选中 pipe.execute() cart_num = redis_conn.hlen("cart_%s" % user_id) # 2.在redis中获取当前用户的购物车商品信息 redis_conn = get_redis_connection("cart") cart_hash = redis_conn.hgetall("cart_%s" % user_id) selected_set = redis_conn.smembers("selected_%s" % user_id)