Django Rest Framework,一个 APIVIEW 的不同端点 URL

Zhe*_*iao 0 api django django-rest-framework

我正在为我的 API 项目使用 Django Rest Framework。现在我有一个带有 post 和 get 方法的 APIVIEW。如何仅为特定的获取或发布添加不同的端点。

class UserView(APIVIEW):
  def get(self, request, format=None):
     .....
     pass

  def post(self, request, format=None):
     .....
     pass
Run Code Online (Sandbox Code Playgroud)

现在在urls.py,我想要这样的东西:

urlpatterns = [
    url(r'^user\/?$', UserView.as_view()),
    url(r'^user_content\/?$', UserView.as_view()),
]
Run Code Online (Sandbox Code Playgroud)

user只接受-GET请求,user_content只接受-POST请求。

ali*_*lix 6

不要那样做。您已经可以在您的APIView. 您可以创建两个不同的APIViews,或者您可以在getpost方法中处理它。你可以尝试这样的事情:

class UserView(APIView):
    def get(self, request, format=None):
        is_user_request = request.data.get('is_user_request', False)
        if is_user_request:
            # Handle your user request here and return JSOn
            return JsonResponse({})
        else:
            # Handle your other requests here
            return JsonResponse({})

    def post(self, request, format=None):
        is_user_content_request = request.data.get('is_user_content_request', False)
        if is_user_content_request:
            # Handle your user content request here and return JSOn
            return JsonResponse({})
        else:
            # Handle your other type requests (if there is any) here
            return JsonResponse({})


urlpatterns = [
    url(r'^api/user$', UserView.as_view()),
]
Run Code Online (Sandbox Code Playgroud)

这只是一个例子。如果您的每个请求都有特定的参数,您可以从这些参数中识别您的请求类型。您不必像我上面那样放置额外的布尔值。检查这种方式,看看它是否适合您。