我正在尝试创建一个用于检查访问令牌和某些条件的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,
}
)
答案 0 :(得分:0)
accesstoken
变量是在方法AccessTokenMixin.dispatch
中本地定义的,因此不在此方法之外定义。
因此,您的TimesheetListApiV2.get
方法应提高:
NameError: name 'accesstoken' is not defined
要解决此问题,只需将accesstoken
替换为self.accesstoken
,以使此变量成为属性。