Django请求MiddleWare在视图中不生效

时间:2019-01-24 15:31:14

标签: python django python-3.x django-rest-framework

我正在研究一个采用JWT令牌,找到关联用户并在请求中将该用户设置为使用令牌的找到用户的解决方案。我的中间件看起来像这样:

class UserTokenMiddleware(object):

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        header_token = request.META.get('HTTP_AUTHORIZATION', None)

        if header_token is not None:
          try:

            token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
            data = {'token': token}
            valid_data = VerifyJSONWebTokenSerializer().validate(data)
            user = valid_data['user']
            request.user = user

          except Token.DoesNotExist:
            pass

        print(request.user.auth_token);
        return self.get_response(request)

它有效! auth_token存在!并将其添加到我的中间件底部,如下所示:

MIDDLEWARE = [
    #Added Last
    "app.middleware.UserTokenMiddleware"
]

现在在这里不起作用。我正在尝试通过已删除的令牌注销,并且需要密钥。所以我有这个:

@action( url_path="logout", detail=False, methods=["get"], renderer_classes=[JSONRenderer])
    def endsession(self, request):
        result = logout(request)
        #request.user.auth_token.delete()
        print("Auth Token") 
        print(request.user.auth_token);
        print(result)
        return Response({"logout": "successful"})

除了我总是收到以下错误:

Exception Type: AttributeError at /v1/users/logout
Exception Value: 'AnonymousUser' object has no attribute 'auth_token'

关于auth_token为什么突然消失并恢复为AnonymousUser的任何线索吗?

1 个答案:

答案 0 :(得分:1)

因为您在视图开始时调用了logout;专门将用户设置为匿名。