使用 Django REST framework 的 Viewsets

简单点说,DRF的Viewsets就允许你将一批功能类似或者有流程的接口写在一个类里面。

比如我有一个流程:需要先A, 后B,再C,后D,完成4个顺序接口,则可以这样使用Viewsets。

view.py

from rest_framework import viewsets
from rest_framework.decorators import list_route
class UserViewSet(viewsets.GenericViewSet):
    """
    A viewset that provides the standard actions
    """

    @list_route(methods=['post'])
    def A(self, request):
        return Response('A')

    @list_route(methods=['get'])
    def B(self, request):
        return Response('B')

    @list_route(methods=['post'])
    def C(self, request):
        return Response('C')

    @list_route(methods=['get'])
    def D(self, request):
        return Response('D')

url.py

from django.conf.urls import url
from rest_framework.routers import DefaultRouter

from rs_account.views import (
    UserViewSet
)

router = DefaultRouter()
router.register(r'user', UserViewSet, base_name='user')

urlpatterns = [
    # search question
]

urlpatterns += router.urls

这样配置完,你就有4个接口URL:

post    /user/A/
get     /user/B/
post    /user/C/
get     /user/D/

DRF 3.8 更新

根据最新的官方文档,在DRF 3.8这个版本使用 @action 代替了 @list_router和@detail_router。

Deprecations
action decorator replaces list_route and detail_route
#5705 list_route and detail_route have been merge into a single action decorator. This improves viewset action introspection, and will allow extra actions to be displayed in the Browsable API in future versions.

Both list_route and detail_route are now pending deprecation. They will be deprecated in 3.9 and removed entirely in 3.10.

The new action decorator takes a boolean detail argument.

Replace detail_route uses with @action(detail=True).
Replace list_route uses with @action(detail=False).
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值