DRF路由组件分析
在之前进行drf开发时,对于路由我们一般进行两种配置:
-
视图继承APIView
from django.urls import path from app01 import views urlpatterns = [ path('api/users/', views.UserView.as_view()), # APIView ]
-
视图继承
ViewSetMixin
(GenericViewSet、ModelViewSet)from django.urls import path, re_path, include from app01 import views urlpatterns = [ path('api/users/', views.UserView.as_view({"get":"list","post":"create"})), path('api/users/<int:pk>/', views.UserView.as_view({"get":"retrieve","put":"update","patch":"partial_update","delete":"destory"})), ]
对于这种形式的路由,drf中提供了更简便的方式:
from rest_framework import routers from app01 import views router = routers.SimpleRouter() # routers.urls 所有的路由信息 router.register(r'api/users', views.UserView) urlpatterns = [ # 其他URL # path('xxxx/', xxxx.as_view()), ] urlpatterns += router.urls
也可以利用include,给URL加前缀:
from django.urls import path, include from rest_framework import routers from app01 import views router = routers.SimpleRouter() router.register(r'users', views.UserView) urlpatterns = [ path('api/', include((router.urls, 'app_name'), namespace='instance_name')), # 其他URL # path('forgot-password/', ForgotPasswordFormView.as_view()), ]
额外的URL
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
class XXXModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = "__all__"
class XXXView(ModelViewSet):
queryset = models.UserInfo.objects.all()
serializer_class = XXXModelSerializer
# detail=False: 生成URL时后面不带id
# @action(detail=False, methods=['get'], url_path="yyy/(?P<xx>\d+)/xxx")
# def get_password(self, request, xx, pk=None):
# print(xx)
# return Response("...")
# @action(detail=True, methods=['get'], url_path="yyy/(?P<xx>\d+)/xxx")
# def set_password(self, request, xx, pk=None):
# print(xx)
# return Response("...")