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("认证超时!")
  • 相关阅读:
    服务注册与发现
    回溯算法
    SpringCloud之远程调用OpenFeign和Ribbon
    SpringCloud之Ribbon负载均衡策略
    Java(Springboot)获取客户端IP地址工具类
    Linux磁盘分区、挂载、查看文件大小
    Dubbo高级进阶Spi应用
    Dubbo监控平台DubboAdmin安装监控
    Dubbo高级进阶Spi应用以及与JDK的Spi区别
    python--装饰器的常见使用
  • 原文地址:https://www.cnblogs.com/wqzn/p/10119972.html
Copyright © 2011-2022 走看看