rest_framework视图组件的接口使用模板

详细源码解析参照:GGGG-XXXX的博客

路由view的中代码:

from .models import Book  #导入对应的表
from .serializers import BookSerializer  #导入对应的序列化器的类

from rest_framework.viewsets import ViewSetMixin
from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView

class ModelViewSet(ViewSetMixin, ListCreateAPIView, RetrieveUpdateDestroyAPIView): #定义一个继承类
    pass
class BookView(ModelViewSet):
queryset = Book.objects.all()          #这个是queryset 必须写成queryset  后面的类名的变量也是一样
serializer_class = BookSerializer

url中代码:

from django.urls import path
from demo.views import BookView
urlpatterns = [
    path("list/",BookView.as_view({"get": "list", "post": "create"})),
    path("list/",BookView.as_view({"get": "retrieve", "patch": "update", "delete": "destroy"})),

]

如果路由特别的情况下,DRF的路由也帮我们封装了自动生成路由的默认类,可以不采用一下方式自动生成路由!

from .views import BookView
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r"book", BookView)    #**注意分发后的url变化,如果路由前面已经做过分发了,此处应该填写router.register("", BookView)**  

urlpatterns = [
    # url(r'^book$', BookView.as_view()),
    # url(r'^book/(?P\d+)$', BookEditView.as_view()),
    # url(r'^book$', BookView.as_view({"get": "list", "post": "create"})),
    # url(r'^book/(?P\d+)$', BookView.as_view({"get": "retrieve", "patch": "update", "delete": "destroy"})),

]
urlpatterns += router.urls

我们可以看到~通过路由框架就特别容易了

如果不是业务需求采用此方式,会把接口数据全部暴露出来, 存在一定的风险

你可能感兴趣的:(rest_framework视图组件的接口使用模板)