Django Rest Framework,一个APIVIEW的不同端点URL [英] Django Rest Framework, different endpoint URL for one APIVIEW

查看:151
本文介绍了Django Rest Framework,一个APIVIEW的不同端点URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的API项目使用Django Rest Framework。现在我有一个APIVIEW与post和get方法。我该如何仅为特定的get或post添加不同的终结点。

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

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

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

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

用户仅接受 GET -request和 user_content 仅接受 POST -request。

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

推荐答案

请勿这样做。您已经可以在 APIView 中单独处理不同类型的请求。您可以创建两个不同的 APIView s,也可以在 get post 方法。您可以尝试执行以下操作:

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.

这篇关于Django Rest Framework,一个APIVIEW的不同端点URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆