gpt4 book ai didi

python - 如何在 Django 中重用函数或类

转载 作者:太空宇宙 更新时间:2023-11-03 21:06:42 25 4
gpt4 key购买 nike

这是我的类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.",
}
)

现在在我的所有类(class)中都有这段代码。

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):
...

关于python - 如何在 Django 中重用函数或类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55351902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com