从resolve()返回的视图函数中获取post()函数

Get post() function from the view function returned by resolve()

我在rest_framework.views.APIView的基础上定义了一个class,并将其作为视图添加到某些url。例如:

from rest_framework.views import APIView
from rest_framework.response import Response
from django.urls import path

class MyApi(APIView):

    def post(self, request):
        # Do something with the request
        print(request.data)
        return Response(status=200)


path('my-url', MyApi.as_view())

在另一个文件中,我想访问那个class的post()函数,但我只知道url。所以我使用django.urls.resolve()函数获取视图函数

from django.urls import resolve
view, args, kwargs = resolve(url)

但是,我不想获取视图函数,而是我在API-Class.

中定义的底层post()函数

是否有任何选项可以在只知道 url 的情况下获得该功能?

我想避免为每个可能的 url.

构建查找

rest_framework.views.APIView 根据请求方法调用其方法之一。所以只能从请求 URL 中获取函数。它需要 URL 和请求 method。例如,如果您向 example/ 发送 POST 请求,它会调用 APIViewpost 方法。如果您使用 GET 方法调用相同的 URL,它会调用视图的 get 方法。

来自 rest_framework.views.APIView source code:

# Get the appropriate handler method
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed

            response = handler(request, *args, **kwargs)

所以我们也可以这样做。

首先,从resolve函数获取视图:

from django.urls import resolve
view, args, kwargs = resolve(request.URL)

然后,从视图中获取处理函数:

if request.method.lower() in view.http_method_names:
    handler = getattr(view, request.method.lower(),None)
else:
    handler = None