DRF,自定義ROUTER類,動態生成路由,禁用drf預設的SimpleRouter七個curd介面路由

hj009zzh發表於2020-09-28

現狀

最近的專案是用DRF框架實現後端的介面,檢視果斷使用modelviewset,而DRF預設的兩個路由生成類routers.SimpleRouter和DefaultRouter,都會預設生成CURD七個介面的路由,專案不需要這些路由,所以決定自己實現一下Router,很簡單,繼承SimpleRouter重寫類屬性routes即可

程式碼

from rest_framework import routers

class CustomRouter(routers.SimpleRouter):
    """
    自定義的動態路由生成類,用於動態生成viewset中detail=False的介面路由,且不生成DRF原生CURD介面預設生成的路由和detail=True的路由
    配合DRF的ModelViewSet實現CBV的介面
    """
    routes = [
        # Dynamically generated list routes. Generated using
        # @action(detail=False) decorator on methods of the viewset.
        routers.DynamicRoute(
            url=r'^{prefix}/{url_path}{trailing_slash}$',
            name='{basename}-{url_name}',
            detail=False,
            initkwargs={}
        ),
    ]

呼叫

from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action

class TestViewSet(ModelViewSet):
    @action(methods=['post'], detial=False)
    def dev(self, request, *args, **kwargs):
        pass

    @action(methods=['get'], detial=False, url_path='test')
    def testing(self, request, *args, **kwargs):
        pass

# urls.py  # 如下配置,只生成test_view/dev 和test_view/test 兩個路由
router = CustomRouter()
router.register(r'test_view', TestViewSet, basename='test_view')
urlpatterns = [] + router.urls

相關文章