Django:在子类中的方法上使用装饰器来处理来自 urls.py 的请求

Django: Using decorators on methods in a subclass to handle requests from urls.py

我曾经有一些大文件,其中包含从 urls.py 调用的修饰函数。这是不可持续的,所以他们被分成控制器,逻辑在其他地方(与这个问题无关)。控制器从主 Controller class 子class 共享频繁的导入和其他共性。 我现在无法使用装饰器函数,最接近的是

AssertionError: The `request` argument must be an instance of `django.http.HttpRequest`, not `api.controllers.FooController.FooController`.

AttributeError: 'functools.partial' object has no attribute '__name__'

使用带有 as_view()get() 和自定义方法都行不通,如下所示。 我试过 @method_decorator(login_required) 等,但没有成功。 我的文件(简化)如下。方法内容不要在意,这里只是为了演示。

api/urls.py:

from django.urls import path
from api.controllers.FooController import FooController
urlpatterns = [
    path("get_foo", FooController,as_view(), name="get_foo")
    path("get_bar", FooController.foo_bar, name="get_bar")
]

api/controllers/Controller.py:

from django.views import View
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from django.http import HttpResponse, JsonResponse, StreamingHttpResponse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

class Controller(View):
    def __init__(self):
        # Set some variables
    # define some methods

api/controllers/FooController.py:

from api.controllers.Controller import *

class FooController(Controller):
    method_decorator(api_view(["GET"]))
    method_decorator(login_required)
    method_decorator(authentication_classes((SessionAuthentication, TokenAuthentication,)))
    method_decorator(permission_classes((IsAuthenticated,)))
    def get(self, request):
        if request.user.is_authenticated:
            return HttpResponse(status=200)
        else:
            return HttpResponse(status=401)

    method_decorator(api_view(["GET"]))
    method_decorator(login_required)
    method_decorator(authentication_classes((SessionAuthentication, TokenAuthentication,)))
    method_decorator(permission_classes((IsAuthenticated,)))
    def foo_bar(self, request):
        if request.user.is_authenticated:
            return JsonResponse({"data": "some data"}, status=200)

如果有人能帮我解决这个问题,非常感谢!

在您的 urls.py 中,使用如下路径:

path("get_foo", FooController.as_view({"get":"get_foo"}), name="get_foo"),

在你的基础中使用 Django 的 APIView Controller.py:

from rest_framework import viewsets
class Controller(viewsets.ViewSet):
    def __init__(self):
        # Code

然后像这样在 FooController.py 中启动你的 FooController class:

class FooController(Controller):
    authentication_classes = [SessionAuthentication, TokenAuthentication]
    permission_classes = [IsAuthenticated]
    def get_foo(self, request):