我正在尝试创建一个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,
}
)
accesstoken
变量在方法AccessTokenMixin.dispatch
中本地定义,因此它不在此方法之外定义。
所以你的TimesheetListApiV2.get
方法应该提出:
NameError: name 'accesstoken' is not defined
要解决这个问题,只需用accesstoken
替换self.accesstoken
,就可以使这个变量成为一个属性。