django 时区设置 redis token缓存策略

from django.utils.timezone import utc
import datetime
datetime.datetime.utcnow().replace(tzinfo=utc)#生成utf格林尼治时间
datetime.timedelta(days=14) 生成14天的日期格式的数字

import redis
import datetime
from app01 import models
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.utils.timezone import utc
redis_conn = redis.Redis(decode_responses=True)

class TokenAuthenticate(BaseAuthentication):
def authenticate(self, request):
token = request.META.get("HTTP_TOKEN")
rds_token = redis_conn.get(token,1)#这里给个1 防止客户端发送请求是如果不携带token时,redis_conn.get(token)会返回一个None; ret = models.Token.objects.filter(key=token, ).first()这里就会报错
if rds_token:
print('缓存')
return rds_token,token
ret = models.Token.objects.filter(key=token, ).first()
if ret :
created_time = ret.created
# token剩余有效期时间
period_of_validity = datetime.timedelta(days=14) + created_time - datetime.datetime.utcnow().replace(
tzinfo=utc)
if period_of_validity > datetime.timedelta(days=3):#假如token有效期大于3,redis中设置token过期时间为3天对应的秒数
redis_conn.set(token,ret.user.username,ex=10)
elif period_of_validity < datetime.timedelta(days=3):
redis_conn.set(token,ret.user.username, ex=int(period_of_validity.total_seconds()))#,假如剩余时间不足三天把剩余天数转换成剩余秒数
else:
raise AuthenticationFailed('token过期')#假如已经没有剩余天数则直接报错,抛出token过期信息
print('数据库')
return ret.user,token
else:raise AuthenticationFailed('token过期')
 
posted @ 2019-04-24 23:06  充电宝宝  阅读(332)  评论(0编辑  收藏  举报