这是我的班级TimesheetListApiV2
有很多这样的类。
@valid_accesstoken_check
class TimesheetListApiV2(APIView):
def get(self, request):
try:
accesstoken=AccessToken.objects.get(
token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '')
)
except ObjectDoesNotExist:
return Response (
{
"status" : False,
"error" : "Wrong Access Token",
"error_message":"You have provided wrong access token.",
}
)
现在我的所有课程中都有这段代码。
try:
accesstoken=AccessToken.objects.get(
token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '')
)
except ObjectDoesNotExist:
return Response (
{
"status" : False,
"error" : "Wrong Access Token",
"error_message":"You have provided wrong access token.",
}
)
我想编写一个函数或类来重用该代码而不是编写代码。但它应该是可行的,即使request
应该通过。即使将来我也会添加更多应该重复使用的代码。
我试着制作这个decorators.py
from django.core.exceptions import ObjectDoesNotExist
from oauth2_provider.models import AccessToken
def valid_accesstoken_check(function):
def wrap(request, *args, **kwargs):
try:
accesstoken=AccessToken.objects.get(
token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '')
)
except ObjectDoesNotExist:
return Response (
{
"status" : False,
"error" : "Wrong Access Token",
"error_message":"You have provided wrong access token.",
}
)
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
但它给出了错误
path('timesheet/list', views.TimesheetListApiV2.as_view(), name='api_v2_timesheet_list'),
AttributeError: 'function' object has no attribute 'as_view'
你的装饰者应该适用于get
方法,而不是类本身:
class TimesheetListApiV2(APIView):
@valid_accesstoken_check
def get(self, request):
...