【问题标题】:Django REST Framework - TokenAuthentication - use of CacheDjango REST Framework - TokenAuthentication - 缓存的使用
【发布时间】:2016-11-04 02:23:10
【问题描述】:

有没有办法在 Django REST Framework 中使用 memcached 进行 TokenAuthentication。

我的用户令牌长时间(例如几个月)保持不变,因此不要为进入我的服务器的每个请求访问数据库并使用缓存的令牌获取用户对象是有意义的。

有没有一种巧妙的方法来实现这一点?

谢谢

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    您可以创建一个custom authentication class 来访问 memcached 而不是您的 DB:

    class ExampleAuthentication(authentication.BaseAuthentication):
        def authenticate(self, request):
            token = request... # get your token here
            if not token:
                return None
    
            try:
                # user = User.objects.get(username=username) -> This is the original code from the link above
                user = ... # get your user based in token here
            except User.DoesNotExist:  # some possible error
                raise exceptions.AuthenticationFailed('No such user')
    
            return (user, None)
    

    然后您可以为每个视图使用自己的身份验证类,即:

    class ExampleApiView(APIView):
        authentication_classes = (CustomTokenAuthentication, )
    
        def get(self, request, *args, **kwargs):
    
            ...
    

    【讨论】:

      猜你喜欢
      • 2013-07-07
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 2016-11-14
      • 2021-04-15
      • 1970-01-01
      相关资源
      最近更新 更多