Mixin无法正常工作 - Django

问题描述 投票:0回答:1

我正在尝试创建一个mixin来检查访问令牌和一些条件。但似乎没有用。即使我在accesstoken里面的TimesheetListApiV2使用那个AccessTokenMixin变量。如何在视图中访问该变量。

class AccessTokenMixin:

    def dispatch(self, request, *args, **kwargs):
        try:
            accesstoken=AccessToken.objects.get(
                        token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '')
                    )

            if not accesstoken.application.company.company_tab_opts:
                return Response (
                    {
                        "status" : False,
                        "error" : "Tab Opts Error",
                        "error_message":"You are not allowed to access it.",
                    }
                )

            return super().dispatch(request, *args, **kwargs)

        except ObjectDoesNotExist:
            return Response (
                {
                    "status" : False,
                    "error" : "Wrong Access Token",
                    "error_message":"You have provided wrong access token.",
                }
            )

class TimesheetListApiV2(AccessTokenMixin, APIView):

    def get(self, request):

        qs = User.objects.exclude(
                        Q(userprofile__user_is_deleted = True) |
                        Q(userprofile__user_company__company_is_deleted=True) 
                    ).filter(
                        Q(userprofile__user_company =accesstoken.application.company) 
                    )
        serializer = TimesheetListSerializer(qs, many=True)

        return Response (
                {
                    "status" : True,
                    "message":"Timesheet Retrieved Successfully.",
                    "result_count": qs.count(),
                    "api_name" : "TimesheetListApiV2",
                    "result": serializer.data,
                }
            )
django django-rest-framework django-views
1个回答
0
投票

accesstoken变量在方法AccessTokenMixin.dispatch中本地定义,因此它不在此方法之外定义。

所以你的TimesheetListApiV2.get方法应该提出:

NameError: name 'accesstoken' is not defined

要解决这个问题,只需用accesstoken替换self.accesstoken,就可以使这个变量成为一个属性。

© www.soinside.com 2019 - 2024. All rights reserved.