django redis配置和简单使用
配置
# 设置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"
使用
# 获取redis连接 red = get_redis_connection('sms_code') code = '%6d' % random.randint(1, 999999) red.setex('phone_%s' % phone, 5 * 60, code, ) red.setex('phone_%s_interval' % phone, 60, code)
redis事务操作
code = '%6d' % random.randint(1, 999999) # 使用事务来操作命令,一条失败全都是失败 # 创建管道 pipe = red.pipeline() # 开启事务 pipe.multi() pipe.setex('phone_%s' % phone, SMS_EXPIRATION_TIME, code, ) pipe.setex('phone_%s_interval' % phone, SMS_INTERVAL_TIME, code) # 执行事务 pipe.execute()