如何在Django中重用函数或类

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

这是我的班级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'
python django python-3.x django-views
1个回答
0
投票

你的装饰者应该适用于get方法,而不是类本身:

class TimesheetListApiV2(APIView):
    @valid_accesstoken_check
    def get(self, request):
    ...
© www.soinside.com 2019 - 2024. All rights reserved.