DRF中新构造的View类的继承一览图,图片引用:https://www.cnblogs.com/hehecat/p/9349427.html
以下是各类的大概说明:
class APIView(View):
"""
推荐!
干净的APIView
"""
class GenericAPIView(views.APIView):
"""
加入了get_object,序列化等
Base class for all other generic views.
"""
class ViewSet(ViewSetMixin, views.APIView):
"""
只重写了as_vieww
The base ViewSet class does not provide any actions by default.
"""
pass
class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
"""
没有提供action,但是加入了get_object,序列化等,另外重写了as_vieww
The GenericViewSet class does not provide any actions by default,
but does include the base set of generic view behavior, such as
the `get_object` and `get_queryset` methods.
"""
pass
最终的封装类ModelViewSet,已经抽象到直接实现了rest api的基本增删改查操作,集成度非常高,路由也比较方便,可以直接注册路由,可以自己编写。
router.register(r'groups', views.GroupViewSet)
# 但因为继承了ViewSetMixin重写了as_view方法,如果自己写路由这时候需要加入action参数。
urlpatterns = [
path('sessions/', views.UserViewSet.as_view({'get': 'list'}))
]
但是
一般情况下,过于抽象的东西可扩展性是很差的,我们为了实现自己想实现的方式,继承APIView类自由开发才是一个灵活的开发方式。
简单看了下逻辑,画了DRF的权限和认证代码逻辑图如下: