Django配置redis缓存
(1)首先安装django-redis
pip install django-redis
(2)在settings中配置如下所示:
# 改配置仅为示例,具体要根据自己需求来配置,比如LOCATION配置项,比如缓存个数,可以配置多个
CACHES = {
"default": { # 省市区数据
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/0",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
"session": { # session
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
"verify_code": { # 验证码
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/2",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
"history": { # 商品浏览记录
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/3",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
"cart": { # 购物车
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/4",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
}
# 修改Django的Session机制使用redis保存,且使用名为'session'的redis配置。(非必须配置)
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "session"
(3)使用redis
# 举一个短信验证码的例子
class SMSCodeView(APIView):
"""短信验证码"""
def get(self,request, mobile):
# 创建redis连接对象
redis_conn = get_redis_connection('verify_code')
send_flag = redis_conn.get('send_flag_%s' % mobile)
if send_flag:
return Response({'message': '获取短信验证码过于频繁,60秒后再试'}, status=status.HTTP_400_BAD_REQUEST)
# 生成验证码
sms_code = '%06d' % random.randint(0, 999999)
logger.info(sms_code)
# 创建redis管道,把操作命令塞进管道,减少redis数据库的连接次数,提高性能
pl = redis_conn.pipeline()
# 把验证码存到redis数据库
pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
# 利用互亿无线发短信
send_sms_code.delay(sms_code, mobile)
# 在redis里存储一个标记,代表这个手机号已发过短信
pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
# 执行管道命令
pl.execute()
return Response({"message": "ok"})