zoukankan      html  css  js  c++  java
  • 使用django 的cache设置token的有效期

      

    from rest_framework.authentication import BaseAuthentication
    from rest_framework.exceptions import AuthenticationFailed
    from api.models import Token
    import datetime
    from django.core.cache import cache
    import pytz
    
    class LoginAuth(BaseAuthentication):
        def authenticate(self, request):
            '''
            1 对token设置14天有效时间
            2 缓存存储
            :param request:
            :return:
            '''
            # print(request.META.get("HTTP_AUTHORIZATION"))
            token=request.META.get("HTTP_AUTHORIZATION")
            # 1 校验是否存在token字符串
            # 1.1 缓存校验
            user=cache.get(token)
            if user:
                print("缓存校验成功")
                return user,token
            # 1.2 数据库校验
            token_obj = Token.objects.filter(key=token).first()
            if not token_obj:
                raise AuthenticationFailed("认证失败!")
    
            # 2 校验是否在有效期内
            print(token_obj.created)    # 2018-1-1- 0 0 0
            now=datetime.datetime.now() # 2018-1-12- 0 0 0
            now = now.replace(tzinfo=pytz.timezone('UTC'))
            print(now-token_obj.created)
            delta=now - token_obj.created
            state=delta < datetime.timedelta(weeks=2)
            print(state)
            if state:
                # 校验成功,写入缓存中
                print("delta",delta)
                delta=datetime.timedelta(weeks=2)-delta
                print(delta.total_seconds())
                cache.set(token_obj.key,token_obj.user,min(delta.total_seconds(),3600*24*7))
                print("数据库校验成功")
                return token_obj.user,token_obj.key
            else:
                raise  AuthenticationFailed("认证超时!")
  • 相关阅读:
    java面试第八天
    java面试第七天
    java面试第六天
    java面试第五天
    java面试第四天
    SpringMVC导出Excel
    75. Autorelease机制及释放时机
    关于 SQLNET.AUTHENTICATION_SERVICES 验证方式的说明
    硬件十万个为什么——运放篇(五)PCB设计技巧
    eclipse到Android Studio的项目迁移
  • 原文地址:https://www.cnblogs.com/wqzn/p/10119972.html
Copyright © 2011-2022 走看看