drf框架路由组件最终写法
drf框架路由组件的使用
注意:路由组件,必须配合视图集使用
一.导入模块
from rest_framework.routers import SimpleRouter
二.创建路由
router = SimpleRouter() # 注册各种接口路由 # 注意:books后面不能带斜杠 # 以后就写视图集的注册即可:BookV3APIView和BookV4APIView都是视图集 router.register('v3/books', views.BookV3APIView, 'book') router.register('v4/books', views.BookV4APIView, 'book') urlpatterns = [ url('',include(router.urls)) ]
from rest_framework.routers import SimpleRouter as DrfSimpleRouter from rest_framework.routers import Route, DynamicRoute class SimpleRouter(DrfSimpleRouter): routes = [ # List route. Route( url=r'^{prefix}{trailing_slash}$', mapping={ 'get': 'list', 'post': 'create', # 注:群增只能自己在视图类中重写create方法,完成区分 'delete': 'multiple_destroy', # 新增:群删 'put': 'multiple_update', # 新增:群整体改 'patch': 'multiple_partial_update' # 新增:群局部改 }, name='{basename}-list', detail=False, initkwargs={'suffix': 'List'} ), # Dynamically generated list routes. Generated using # @action(detail=False) decorator on methods of the viewset. DynamicRoute( url=r'^{prefix}/{url_path}{trailing_slash}$', name='{basename}-{url_name}', detail=False, initkwargs={} ), # Detail route. Route( url=r'^{prefix}/{lookup}{trailing_slash}$', mapping={ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }, name='{basename}-detail', detail=True, initkwargs={'suffix': 'Instance'} ), # Dynamically generated detail routes. Generated using # @action(detail=True) decorator on methods of the viewset. DynamicRoute( url=r'^{prefix}/{lookup}/{url_path}{trailing_slash}$', name='{basename}-{url_name}', detail=True, initkwargs={} ), ]
# 用路由组件配置,形成的映射关系是 /user/center/ => list | user/center/(pk)/ => retrieve # router.register('user/center', views.UserCenterViewSet, 'center') urlpatterns = [ # ... # 让 /user/center/ => 单查,不能走路由组件,只能自定义配置映射关系 url('^user/center/$', views.UserCenterViewSet.as_view({'get': 'user_center'})), ]
from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response class UserCenterViewSet(GenericViewSet): permission_classes = [IsAuthenticated, ] queryset = models.User.objects.filter(is_active=True).all() serializer_class = serializers.UserCenterSerializer def user_center(self, request, *args, **kwargs): # request.user就是前台带token,在经过认证组件解析出来的, # 再经过权限组件IsAuthenticated的校验,所以request.user一定有值,就是当前登录用户 serializer = self.get_serializer(request.user) return Response(serializer.data)