视图
视图
Django REST framwork 提供的视图的主要作用:
-
控制序列化器的执行(检验、保存、转换数据)
-
控制数据库查询的执行
-
调用请求类和响应类[这两个类也是由drf帮我们再次扩展了一些功能类。]
创建一个子应用req
python manage.py startapp httpdemo
REST framework 提供了Parser解析器类,在接收到request请求后会自动根据Content-Type指明的请求数据类型(如JSON、表单等)将请求数据进行parse解析,解析为类字典[QueryDict]对象保存到Request对象中。
Request对象的数据是自动根据前端发送数据的格式进行解析之后的结果。
无论前端发送的哪种格式的数据,我们都可以以统一的方式读取数据。
request.data 返回解析之后的请求体数据。类似于Django中标准的request.POST
-
包含了解析之后的文件和非文件数据
-
包含了对POST、PUT、PATCH请求方式解析后的数据
-
利用了REST framework的parsers解析器,不仅支持表单类型数据,也支持JSON数据
rest_framework.response.Response
REST framework提供了一个响应类 Response ,使用该类构造响应对象时,响应的具体数据内容会被转换(render渲染器对象)成符合前端需求的类型。
restframework/settings.py
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( # 默认响应渲染类 'rest_framework.renderers.JSONRenderer', # json渲染器 'rest_framework.renderers.BrowsableAPIRenderer', # 浏览API渲染器 ) }
Response(data, status=None, template_name=None, headers=None, content_type=None)
使用方式
from rest_framework.views import APIView from rest_framework import status from rest_framework.response import Response class StudentAPIView(APIView): def get(self,request): """获取所有学生信息""" print(request) # rest_framework.request.Request print(request._request) # django原来提供的request对象 return Response(data={"message":"ok"},status=status.HTTP_400_BAD_REQUEST,headers={"company":"oldboy"})
data不能是复杂结构的数据,如Django的模型类对象,对于这样的数据我们可以使用Serializer序列化器序列化处理后(转为了Python字典类型)再传递给data参数。
参数说明:
- data: 为响应准备的序列化处理后的数据;
- status: 状态码,默认200;
- template_name: 模板名称,如果使用HTMLRenderer 时需指明;
- headers: 用于存放响应头信息的字典;
- content_type: 响应数据的Content-Type,通常此参数无需传递,REST framework会根据前端所需类型数据来设置该参数。
1).data 传给response对象的序列化后,但尚未render处理的数据 2).status_code 状态码的数字 3).content 经过render处理后的响应数据
HTTP_100_CONTINUE
HTTP_101_SWITCHING_PROTOCOLS
HTTP_200_OK
HTTP_201_CREATED
HTTP_202_ACCEPTED
HTTP_203_NON_AUTHORITATIVE_INFORMATION
HTTP_204_NO_CONTENT
HTTP_205_RESET_CONTENT
HTTP_206_PARTIAL_CONTENT
HTTP_207_MULTI_STATUS
HTTP_300_MULTIPLE_CHOICES
HTTP_301_MOVED_PERMANENTLY
HTTP_302_FOUND
HTTP_303_SEE_OTHER
HTTP_304_NOT_MODIFIED
HTTP_305_USE_PROXY
HTTP_306_RESERVED
HTTP_307_TEMPORARY_REDIRECT
HTTP_400_BAD_REQUEST
HTTP_401_UNAUTHORIZED
HTTP_402_PAYMENT_REQUIRED
HTTP_403_FORBIDDEN
HTTP_404_NOT_FOUND
HTTP_405_METHOD_NOT_ALLOWED
HTTP_406_NOT_ACCEPTABLE
HTTP_407_PROXY_AUTHENTICATION_REQUIRED
HTTP_408_REQUEST_TIMEOUT
HTTP_409_CONFLICT
HTTP_410_GONE
HTTP_411_LENGTH_REQUIRED
HTTP_412_PRECONDITION_FAILED
HTTP_413_REQUEST_ENTITY_TOO_LARGE
HTTP_414_REQUEST_URI_TOO_LONG
HTTP_415_UNSUPPORTED_MEDIA_TYPE
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
HTTP_417_EXPECTATION_FAILED
HTTP_422_UNPROCESSABLE_ENTITY
HTTP_423_LOCKED
HTTP_424_FAILED_DEPENDENCY
HTTP_428_PRECONDITION_REQUIRED
HTTP_429_TOO_MANY_REQUESTS
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS
HTTP_500_INTERNAL_SERVER_ERROR
HTTP_501_NOT_IMPLEMENTED
HTTP_502_BAD_GATEWAY
HTTP_503_SERVICE_UNAVAILABLE
HTTP_504_GATEWAY_TIMEOUT
HTTP_505_HTTP_VERSION_NOT_SUPPORTED
HTTP_507_INSUFFICIENT_STORAGE
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED
2个视图基类
创建一个新应用
python manage.py startapp baseview
rest_framework.views.APIView
APIView是REST framework提供的所有视图的基类,继承自Django的View父类。
APIView与View的不同之处在于:
-
传入到视图方法中的是REST framework的Request对象,而不是Django的HttpRequeset对象;
-
视图方法可以返回REST framework的Response对象,视图会为响应数据设置(render)符合前端要求的格式;
-
任何APIException异常都会被捕获到,并且处理成合适的响应信息;
-
支持定义的属性
模型序列化器
# 创建序列化器类,回头会在试图中被调用 from rest_framework import serializers from .models import Student class StudentModelSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__"
举例:
from rest_framework.views import APIView from students.models import Student from students.serializers import StudentModelSerializer from rest_framework.response import Response from rest_framework import status class StudentAPIView(APIView): # 序列化 def get(self,request): """提供所有学生信息""" student_list = Student.objects.all() serializer = StudentModelSerializer(instance=student_list,many=True) return Response(serializer.data) # 反序列化 def post(self,request): """添加学生数据""" data = request.data serializer=StudentModelSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() print(1111,serializer.data) return Response(serializer.data,status=status.HTTP_201_CREATED)
rest_framework.generics.GenericAPIView
举例:
"""GenericAPIView 通用视图类""" from rest_framework.generics import GenericAPIView class StudentGenericAPIView(GenericAPIView): serializer_class = StudentModelSerializer queryset = Student.objects.all() def get(self,request): """获取所有学生信息""" serializer = self.get_serializer(instance=self.get_queryset(), many=True) return Response(serializer.data) def post(self,request): """添加学生数据""" data = request.data serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
提供的关于序列化器使用的属性与方法
属性:
get_serializer_class(self)
返回序列化器类,默认返回serializer_class,可以重写,例如:
def get_serializer_class(self): if self.request.user.is_staff: return FullAccountSerializer return BasicAccountSerializer
注意,该方法在提供序列化器对象的时候,会向序列化器对象的context属性补充三个数据:request、format、view,这三个数据对象可以在定义序列化器时使用。
-
request 当前视图的请求对象
-
view 当前请求的类视图对象
-
format 当前请求期望返回的数据格式
提供的关于数据库查询的属性与方法
属性:
方法:
返回视图使用的查询集,主要用来提供给Mixin扩展类使用,是列表视图与详情视图获取数据的基础,默认返回queryset
属性,可以重写,例如:
def get_queryset(self): user = self.request.user return user.accounts.all()
get_object(self)
在试图中可以调用该方法获取详情信息的模型类对象。
若详情访问的模型类对象不存在,会返回404。
该方法会默认使用APIView提供的check_object_permissions方法检查当前对象是否有权限被访问。
举例:
# url(r'^books/(?P<pk>\d+)/$', views.BookDetailView.as_view()), class BookDetailView(GenericAPIView): queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer def get(self, request, pk): book = self.get_object() # get_object()方法根据pk参数查找queryset中的数据对象 serializer = self.get_serializer(book) return Response(serializer.data)
其他可以设置的属性
-
-
filter_backends 指明过滤控制后端
实例:
新建一个子应用。
python manage.py startapp gen
代码:
from rest_framework.generics import GenericAPIView from students.models import Student from .serializers import StudentModelSerializer, StudentModel2Serializer from rest_framework.response import Response class StudentsGenericAPIView(GenericAPIView): # 本次视图类中要操作的数据[必填] queryset = Student.objects.all() # 本次视图类中要调用的默认序列化器[玄天] serializer_class = StudentModelSerializer def get(self, request): """获取所有学生信息""" serializer = self.get_serializer(instance=self.get_queryset(), many=True) return Response(serializer.data) def post(self,request): data = request.data serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) instance = serializer.save() serializer = self.get_serializer(instance=instance) return Response(serializer.data) class StudentGenericAPIView(GenericAPIView): queryset = Student.objects.all() serializer_class = StudentModelSerializer def get_serializer_class(self): """重写获取序列化器类的方法""" if self.request.method == "GET": return StudentModel2Serializer else: return StudentModelSerializer # 在使用GenericAPIView视图获取或操作单个数据时,视图方法中的代表主键的参数最好是pk def get(self,request,pk): """获取一条数据""" serializer = self.get_serializer(instance=self.get_object()) return Response(serializer.data) def put(self,request,pk): data = request.data serializer = self.get_serializer(instance=self.get_object(),data=data) serializer.is_valid(raise_exception=True) serializer.save() serializer = self.get_serializer(instance=self.get_object()) return Response(serializer.data)
序列化器类:
from rest_framework import serializers from students.models import Student class StudentModelSerializer(serializers.ModelSerializer): class Meta: model= Student fields = "__all__" class StudentModel2Serializer(serializers.ModelSerializer): class Meta: model= Student fields = ("name","class_null")
作用:
减少代码量。
这五个扩展类需要搭配GenericAPIView父类,因为五个扩展类的实现需要调用GenericAPIView提供的序列化器与数据库查询的方法。
"""使用GenericAPIView和视图扩展类进行代码的简写 在drf中提供了5个不同的视图扩展类,里面封装了5个不同的http请求方法,用于和GenericAPIView实现代码的简写 """ CreateModelMixin #[添加一条数据] ListModelMixin #[获取所有数据] RetrieveModelMixin #[获取一条数据] DestroyModelMixin #[删除一条数据] UpdateModelMixin #[更新一条数据]
queryset 和 serializer_class变量名为固定写法
1)
该Mixin的list方法会对数据进行过滤和分页。
举例:
from rest_framework.mixins import ListModelMixin class BookListView(ListModelMixin, GenericAPIView): queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer def get(self, request): return self.list(request)
源代码:
class ListModelMixin(object): """ List a queryset. """ def list(self, request, *args, **kwargs): # 过滤 queryset = self.filter_queryset(self.get_queryset()) # 分页 page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) # 序列化 serializer = self.get_serializer(queryset, many=True) return Response(serializer.data)
创建视图扩展类,提供create(request, *args, **kwargs)
方法快速实现创建资源的视图,成功返回201状态码。
如果序列化器对前端发送的数据验证失败,返回400错误。
举例:
from rest_framework.mixins import ListModelMixin class BookListView(CreateModelMixin, GenericAPIView): queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer def post(self,request): """添加学生数据""" return self.create(request)
源代码:
class CreateModelMixin(object): """ Create a model instance. """ def create(self, request, *args, **kwargs): # 获取序列化器 serializer = self.get_serializer(data=request.data) # 验证 serializer.is_valid(raise_exception=True) # 保存 self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() def get_success_headers(self, data): try: return {'Location': str(data[api_settings.URL_FIELD_NAME])} except (TypeError, KeyError): return {}
获取一条数据
如果存在,返回200, 否则返回404。
举例:
class BookDetailView(RetrieveModelMixin, GenericAPIView): queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer def get(self, request, pk): return self.retrieve(request,pk)
源代码:
class RetrieveModelMixin(object): """ Retrieve a model instance. """ def retrieve(self, request, *args, **kwargs): # 获取对象,会检查对象的权限 instance = self.get_object() # 序列化 serializer = self.get_serializer(instance) return Response(serializer.data)
更新一条数据
更新视图扩展类,提供update(request, *args, **kwargs)方法,可以快速实现更新一个存在的数据对象。
成功返回200,序列化器校验数据失败时,返回400错误。
举例:
class Student3GenericAPIView(GenericAPIView,UpdateModelMixin): serializer_class = StudentModelSerializer queryset = Student.objects.all() def put(self,request,pk): """更新一条数据""" return self.update(request,pk)
源代码:
class UpdateModelMixin(object): """ Update a model instance. """ def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): # If 'prefetch_related' has been applied to a queryset, we need to # forcibly invalidate the prefetch cache on the instance. instance._prefetched_objects_cache = {} return Response(serializer.data) def perform_update(self, serializer): serializer.save() def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs)
删除一条数据
成功返回204,不存在返回404。
举例:
class Student3GenericAPIView(GenericAPIView,DestroyModelMixin): serializer_class = StudentModelSerializer queryset = Student.objects.all() def delete(self,request,pk): return self.destroy(request,pk)
源代码
class DestroyModelMixin(object): """ Destroy a model instance. """ def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) def perform_destroy(self, instance): instance.delete()
使用GenericAPIView和视图扩展类,实现api接口,代码:
"""GenericAPIView结合视图扩展类实现api接口""" from rest_framework.mixins import ListModelMixin,CreateModelMixin class Students2GenericAPIView(GenericAPIView,ListModelMixin,CreateModelMixin): # 本次视图类中要操作的数据[必填] queryset = Student.objects.all() # 本次视图类中要调用的默认序列化器[玄天] serializer_class = StudentModelSerializer def get(self, request): """获取多个学生信息""" return self.list(request) def post(self,request): """添加学生信息""" return self.create(request) from rest_framework.mixins import RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin class Student2GenericAPIView(GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin): queryset = Student.objects.all() serializer_class = StudentModelSerializer # 在使用GenericAPIView视图获取或操作单个数据时,视图方法中的代表主键的参数最好是pk def get(self,request,pk): """获取一条数据""" return self.retrieve(request,pk) def put(self,request,pk): """更新一条数据""" return self.update(request,pk) def delete(self,request,pk): """删除一条数据""" return self.destroy(request,pk)
提供 post 方法
继承自: GenericAPIView、CreateModelMixin
2)ListAPIView
提供 get 方法
继承自:GenericAPIView、ListModelMixin
3)RetrieveAPIView
提供 get 方法
继承自: GenericAPIView、RetrieveModelMixin
4)DestoryAPIView
提供 delete 方法
继承自:GenericAPIView、DestoryModelMixin
5)UpdateAPIView
提供 put 和 patch 方法
继承自:GenericAPIView、UpdateModelMixin
6)RetrieveUpdateAPIView
提供 get、put、patch方法
继承自: GenericAPIView、RetrieveModelMixin、UpdateModelMixin
7)RetrieveUpdateDestoryAPIView
提供 get、put、patch、delete方法
继承自:GenericAPIView、RetrieveModelMixin、UpdateModelMixin、DestoryModelMixin
总结
CreateAPIView与RetrieveUpdateDestroyAPIView不能存在于一个类中,内置get有冲突
所以这并不是最简洁的代码
"""在上面的使用过程中,都是视图类继承GenericAPIView和视图扩展类来实现简写的 但是,简写的不够彻底,所以在drf中还可以进一步简写, drf中基于GenericAPIView和视图扩展类,衍生出了多个视图子类 CreateAPIView 添加一条数据 ListAPIView 获取所有数据 RetrieveAPIView 获取一条数据 UpdateAPIView 更新一条数据 DestroyAPIView 删除一条数据 RetrieveUpdateDestroyAPIView RetrieveUpdateAPIView """ from rest_framework.generics import ListAPIView,CreateAPIView,UpdateAPIView,RetrieveAPIView, DestroyAPIView, RetrieveUpdateDestroyAPIView class Student4GenericAPIView(ListAPIView,CreateAPIView): serializer_class = StudentModelSerializer queryset = Student.objects.all() class Student5GenericAPIView(RetrieveUpdateDestroyAPIView): serializer_class = StudentModelSerializer queryset = Student.objects.all()
使用视图集ViewSet,可以将一系列逻辑相关的动作放到一个类中:
-
list() 提供一组数据
-
retrieve() 提供单个数据
-
create() 创建数据
-
update() 保存数据
-
destory() 删除数据
ViewSet视图集类不再实现get()、post()等方法,而是实现动作 action 如 list() 、create() 等。
def list(self,request):
class BookInfoViewSet(viewsets.ViewSet): def list(self, request): books = BookInfo.objects.all() serializer = BookInfoSerializer(books, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): try: books = BookInfo.objects.get(id=pk) except BookInfo.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = BookInfoSerializer(books) return Response(serializer.data)
在路由设置是
urlpatterns = [ url(r'^books/$', BookInfoViewSet.as_view({'get':'list'}), url(r'^books/(?P<pk>\d+)/$', BookInfoViewSet.as_view({'get': 'retrieve'}) ]
继承自APIView与ViewSetMixin
,作用也与APIView基本类似,提供了身份认证、权限校验、流量管理等。
在ViewSet中,没有提供任何动作action方法,需要我们自己实现action方法。
路由
urlpatterns = [ # 视图集中的方法和地址,以及http请求的绑定都是通过在as_view里面完成的 # 基本视图集 ViewSet path("students/", views.StudentAPIViewSet.as_view({"get":"get_all"})), re_path("students/(?P<pk>\d+)/", views.StudentAPIViewSet.as_view({"get":"get_one"})), ]
views
from students.models import Student from students.serializers import StudentModelSerializer from rest_framework.viewsets import ViewSet from rest_framework.response import Response class StudentAPIViewSet(ViewSet): def get_one(self,request,pk): """获取一个学生信息""" student = Student.objects.get(pk=pk) serializer = StudentModelSerializer(instance=student) return Response(serializer.data) def get_all(self,request): """获取多个学生信息""" student_list = Student.objects.all() serializer = StudentModelSerializer(instance=student_list, many=True) return Response(serializer.data)
GenericViewSet就帮助我们完成了这样的继承工作,继承自GenericAPIView与ViewSetMixin,在实现了调用as_view()时传入字典(如{'get':'list'}
)的映射处理工作的同时,还提供了GenericAPIView提供的基础方法,可以直接搭配Mixin扩展类使用。
举例:
路由
# 通用视图集 GenericViewSet path("students1/", views.Student1GenericViewSet.as_view({"get": "list"})), re_path("students1/(?P<pk>\d+)/", views.Student1GenericViewSet.as_view({"get": "retrieve"})),
views
from students.models import Student from students.serializers import StudentModelSerializer from rest_framework.viewsets import GenericViewSet from rest_framework.response import Response class Student1GenericViewSet(GenericViewSet): queryset = Student.objects.all() serializer_class = StudentModelSerializer def retrieve(self,request,pk): """获取一个学生信息""" serializer = self.get_serializer( instance= self.get_object() ) return Response(serializer.data) def list(self,request): """获取多个学生信息""" serializer = self.get_serializer(instance=self.get_queryset(), many=True) return Response(serializer.data)
2.2)通用视图集 和 视图扩展类组合使用
GenericViewSet 和 视图扩展类mixins 配合
路由
# 通用视图集 和 视图扩展类组合使用 path("students2/", views.Student2GenericViewSet.as_view({"get": "list"})), path("students2/top/", views.Student2GenericViewSet.as_view({"get": "get_top_3"})), re_path("students2/(?P<pk>\d+)/", views.Student2GenericViewSet.as_view({"get": "retrieve"})),
view
from rest_framework.viewsets import GenericViewSet from rest_framework.mixins import ListModelMixin,RetrieveModelMixin class Student2GenericViewSet(RetrieveModelMixin, ListModelMixin, GenericViewSet): queryset = Student.objects.all() serializer_class = StudentModelSerializer def get_top_3(self,request): student_list = self.get_queryset()[:3] serializer = self.get_serializer(instance=student_list, many=True) return Response(serializer.data)
# 只读视图集 path("students3/", views.Student3GenericViewSet.as_view({"get": "list"})), re_path("students3/(?P<pk>\d+)/", views.Student3GenericViewSet.as_view({"get": "retrieve"})),
view
"""只读视图集类 ReadOnlyModelViewSet""" from rest_framework.viewsets import ReadOnlyModelViewSet class Student3GenericViewSet(ReadOnlyModelViewSet): queryset = Student.objects.all() serializer_class = StudentModelSerializer
4)ModelViewSet 模型视图集类
路由
# 模型视图集 path("students4/", views.Student4GenericViewSet.as_view({"get": "list","post":"create"})), re_path("students4/(?P<pk>\d+)/", views.Student4GenericViewSet.as_view({"get": "retrieve","delete":"destroy","put":"update"})),
views
"""模型视图集类 ModelViewSet""" from rest_framework.viewsets import ModelViewSet class Student4GenericViewSet(ModelViewSet): queryset = Student.objects.all() serializer_class = StudentModelSerializer
在视图集中,我们可以通过action对象属性来获取当前请求视图集时的action动作是哪个
self.action
from rest_framework.viewsets import ModelViewSet from students.models import Student from .serializers import StudentModelSerializer from rest_framework.response import Response class StudentModelViewSet(ModelViewSet): queryset = Student.objects.all() serializer_class = StudentModelSerializer def get_new_5(self,request): """获取最近添加的5个学生信息""" # 操作数据库 print(self.action) # 获取本次请求的视图方法名 通过路由访问到当前方法中.可以看到本次的action就是请求的方法名
路由Routers
对于视图集ViewSet,我们除了可以自己手动指明请求方式与动作action之间的对应关系外,还可以使用Routers来帮助我们快速实现路由信息。
REST framework提供了两个router
SimpleRouter
DefaultRouter
1).创建router对象,并注册视图集,例如
from rest_framework import routers router = routers.DefaultRouter() router.register(r'router_stu', StudentModelViewSet, base_name='student')
register(prefix, viewset, base_name)
-
prefix 该视图集的路由前缀
-
viewset 视图集
-
如上述代码会形成的路由如下:
^books/$ name: book-list
^books/{pk}/$ name: book-detail
2)添加路由数据
可以有两种方式:
urlpatterns = [
...
]
urlpatterns += router.urls
或
urlpatterns = [ ... url(r'^', include(router.urls)) ]
上面的代码就成功生成了路由地址[增/删/改/查一条/查多条的功能],但是不会自动我们在视图集自定义方法的路由。
以action装饰器装饰的方法名会作为action动作名,与list、retrieve等同。
action装饰器可以接收两个参数:
-
-
detail
: 声明该action的路径是否与单一资源对应,及是否是
xxx/<pk>/action方法名/
-
-
False 表示路径格式是xxx/action方法名/
methods 设置当前方法允许哪些http请求访问当前视图方法
detail 设置当前视图方法是否是操作一个数据
detail为True,表示路径名格式应该为 router_stu/{pk}/login/
detail为False 表示路径名格式应该为 router_stu/get_new_5/
实例
url
# 基于action装饰器和路由类来生成路由,达到简写的目的 # SimpleRouter 和 DefaultRouter 作用:为视图集生成url路由 from rest_framework.routers import SimpleRouter, DefaultRouter router = DefaultRouter() # 注册视图集,生成视图集对应的路由 # router.register("路由前缀","视图集类","可选参数:路由别名前缀") router.register("students6",views.Student6APIViewSet,"students6") router.register("students7",views.Student7GenericViewSet,"students7") # 生成的路由 # print(router.urls) # /students6/get_all Student6APIViewSet.get_all # /students6/<pk>/get_one Student6APIViewSet.get_one urlpatterns = urlpatterns + router.urls
view
下面是两种方式的展示 基础视图 模型视图集类
基础视图
"""使用action装饰器来简写路由""" from rest_framework.decorators import action class Student6APIViewSet(ViewSet): @action(methods=["get"],detail=True) def get_one(self,request,pk): """获取一个学生信息""" student = Student.objects.get(pk=pk) serializer = StudentModelSerializer(instance=student) return Response(serializer.data) @action(methods=["get"], detail=False) # detail表示设置router路由类在生成路由时是否要加上主键pk到url地址中 def get_all(self,request): """获取多个学生信息""" """在视图集中,因为自定义视图方法的名字会各种各样,所以我们需要在视图中获取当前客户端请求的视图方法名,则可以使用 self.action属性来查看""" print(self.action) # get_all student_list = Student.objects.all() serializer = StudentModelSerializer(instance=student_list, many=True) return Response(serializer.data)
模型视图集类
"""如果不使用action自定义方法,可以直接使用路由类直接生成而不需要借助action""" from rest_framework.viewsets import ModelViewSet class Student7GenericViewSet(ModelViewSet): queryset = Student.objects.all() serializer_class = StudentModelSerializer
DefaultRouter与SimpleRouter的区别是,DefaultRouter会多附带一个默认的API根视图,返回一个包含所有列表视图的超链接响应数据。