Django Rest Framework, different endpoint URL for

2019-08-25 06:28发布

问题:

I am using Django Rest Framework for my API project. Now i have one APIVIEW with post and get method. How can i add different endpoint only for a particular get or post.

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

  def post(self, request, format=None):
     .....
     pass

Now in the urls.py, I want something like this:

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

user only accept GET-request and user_content only accept POST-request.

回答1:

Do not do that. You already can handle different types of request separately in your APIView. You can create two different APIViews, or you can handle this in get or post methods. You can try something like this:

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()),
]

This is just an example. If there are specific parameters for your each requests, you can identify your request's type from those parameters. You don't have to put extra boolean values like i did above. Check this way and see if that works for you.