一、URL控制(出自https://www.cnblogs.com/neymargoal/p/9839018.html)
-
自定义路由(原始方式django版)
url.pyfrom django.conf.urls import url from app01 import views urlpatterns = [ url(r'^books/$', views.BookView.as_view()), url(r'^books/(?P<pk>\d+)$', views.BookDetailView.as_view()), ]
class BookView(APIView): def get(self, request): book_list = models.Book.objects.all() bs = BookSerializers(book_list, many=True) return Response(bs.data) def post(self, request): # 添加一条数据 print(request.data) bs=BookSerializers(data=request.data) if bs.is_valid(): bs.save() # 生成记录 return Response(bs.data) else: return Response(bs.errors) class BookDetailView(APIView): def get(self,request,pk): book_obj=models.Book.objects.filter(pk=pk).first() bs=BookSerializers(book_obj,many=False) return Response(bs.data) def put(self,request,pk): book_obj = models.Book.objects.filter(pk=pk).first() bs=BookSerializers(data=request.data,instance=book_obj) if bs.is_valid(): bs.save() # update return Response(bs.data) else: return Response(bs.errors) def delete(self,request,pk): models.Book.objects.filter(pk=pk).delete() return Response("")
-
半自动路由(由视图类继承ModelViewSet)
url.py(两个路由指向同一个视图)
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^publish/$', views.PublishView.as_view({'get':'list','post':'create'})), url(r'^publish/(?P<pk>\d+)/$', views.PublishView.as_view({'get':'retrieve','put':'update','delete':'destroy'})), ]
from rest_framework.viewsets import ModelViewSet class PublishView(ModelViewSet): queryset=models.Publish.objects.all() serializer_class=PublishSerializers
-
全自动路由(自动生成路由)
views.pyfrom rest_framework.viewsets import ModelViewSet class PublishView(ModelViewSet): queryset=models.Publish.objects.all() serializer_class=PublishSerializers
from django.conf.urls import url,include from app01 import views from rest_framework import routers router=routers.DefaultRouter() # 两个参数,一个是匹配的路由,一个是视图中写的CBV的类 router.register('publish',views.PublishView) # router.register('author',views.AuthorView) # router.register('book',views.BookView) urlpatterns = [ # http://127.0.0.1:8000/publish/format=json(渲染器通过这个判断,返回渲染的页面) # url(r'^publish/', views.PublishView.as_view({'get':'list','post':'create'})), # http://127.0.0.1:8000/publish.json(渲染器通过这个判断,返回渲染的页面) # url(r'^publish\.(?P<format>\w+)$', views.PublishView.as_view({'get':'list','post':'create'})), # 可以用 以下方式访问 # 1 http://127.0.0.1:8000/publish/ # 2 http://127.0.0.1:8000/publish.json # 3 http://127.0.0.1:8000/publish/3 # 4 http://127.0.0.1:8000/publish/3.json url(r'',include(router.urls)) ]
二、分页
-
简单分页(常用)
需求:查看第n页,每页显示n条
urls.pyurl(r'^pager/$', views.Pager.as_view()),
Serializers类
class BookSerializer1(serializers.ModelSerializer): class Meta: model=models.Book # fields="__all__" exclude=('authors',)
REST_FRAMEWORK = { # 每页显示两条 'PAGE_SIZE':2 }
1.使用默认配置
views.pyfrom rest_framework.pagination import PageNumberPagination # url=http://127.0.0.1:8000/pager/?page=2&size=3,size无效 class Pager(APIView): def get(self,request,*args,**kwargs): # 获取所有数据 ret=models.Book.objects.all() # 创建分页对象 page=PageNumberPagination() # 在数据库中获取分页的数据 page_list=page.paginate_queryset(ret,request,view=self) # 对分页进行序列化 ser=BookSerializer1(instance=page_list,many=True) return Response(ser.data)
2.自定义(继承PageNumberPagination类,重写属性)
# url=http://127.0.0.1:8000/pager/?page=2&size=3 # size=30,无效,最多5条 class Mypage(PageNumberPagination): page_size = 2 page_query_param = 'page' # 定制传参 page_size_query_param = 'size' # 最大一页的数据 max_page_size = 5 class Pager(APIView): def get(self,request,*args,**kwargs): # 获取所有数据 ret=models.Book.objects.all() # 创建分页对象 page=Mypage() # 在数据库中获取分页的数据 page_list=page.paginate_queryset(ret,request,view=self) # 对分页进行序列化 ser=BookSerializer1(instance=page_list,many=True) # return Response(ser.data) # 这个也是返回Response对象,但是比基本的多了上一页,下一页,和总数据条数(了解即可) return page.get_paginated_response(ser.data)
特别说明
# 1 再setting里配置每页条数 # 2 写一个类,继承它,属性重写 # 3 再对象里修改 ''' 每页显示多少条api_settings.PAGE_SIZE page_size = 查询指定页码的参数 page_query_param = 'page' 指定每页显示条数 page_size_query_param = None 限制每页显示最大条数 max_page_size = None '''
-
偏移分页
需求:在第n个位置,向后查看n条数据
# http://127.0.0.1:8000/pager/?offset=4&limit=3 from rest_framework.pagination import LimitOffsetPagination # 也可以自定制,同简单分页 class Pager(APIView): def get(self,request,*args,**kwargs): # 获取所有数据 ret=models.Book.objects.all() # 创建分页对象 page=LimitOffsetPagination() # 在数据库中获取分页的数据 page_list=page.paginate_queryset(ret,request,view=self) # 对分页进行序列化 ser=BookSerializer1(instance=page_list,many=True) # return page.get_paginated_response(ser.data) return Response(ser.data)
特别声明
# 1 再setting里配置每页条数 # 2 写一个类,继承它,属性重写 # 3 再对象里修改 ''' default_limit:默认显示多少条 max_limit:最大显示多少条 limit_query_param:重新命名limit(limit=4:表明显示四条,受max_limit的限制) offset_query_param:指定查询的标杆名(offset=1:表明从第二条开始,往后偏移) '''
-
加密分页(效率高,且安全)
需求:加密分页,只能看上一页和下一页
from rest_framework.pagination import CursorPagination # 看源码,是通过sql查询,大于id和小于id class Pager(APIView): def get(self,request,*args,**kwargs): # 获取所有数据 ret=models.Book.objects.all() # 创建分页对象 page=CursorPagination() page.ordering='nid' # 在数据库中获取分页的数据 page_list=page.paginate_queryset(ret,request,view=self) # 对分页进行序列化 ser=BookSerializer1(instance=page_list,many=True) # 可以避免页码被猜到 return page.get_paginated_response(ser.data)
特别声明
# 1 再setting里配置每页条数 # 2 写一个类,继承它,属性重写 # 3 再对象里修改 ''' cursor_query_param = 'cursor':查询的名字 page_size = api_settings.PAGE_SIZE:每页显示的条数 ordering = '-created' :按谁排序 '''
三、响应器
-
什么是响应器
根据 用户请求URL 或 用户可接受的类型,筛选出合适的 渲染组件。
用户请求URL:
http://127.0.0.1:8000/test/?format=json
http://127.0.0.1:8000/test.json -
内置渲染器
(1)显示json格式:JSONRenderer
访问URL: http://127.0.0.1:8000/test/?format=json http://127.0.0.1:8000/test.json http://127.0.0.1:8000/test/
(2)默认显示格式:BrowsableAPIRenderer(可以修改它的html文件)
访问URL: http://127.0.0.1:8000/test/?format=api http://127.0.0.1:8000/test.api http://127.0.0.1:8000/test/
(3)表格方式:AdminRenderer
访问URL: http://127.0.0.1:8000/test/?format=admin http://127.0.0.1:8000/test.admin http://127.0.0.1:8000/test/
(4)form表单方式:HTMLFormRenderer
访问URL: http://127.0.0.1:8000/test/?format=form http://127.0.0.1:8000/test.form http://127.0.0.1:8000/test/
-
局部响应器
from rest_framework.renderers import HTMLFormRenderer,BrowsableAPIRenderer class BookDetailView(APIView): renderer_classes = [HTMLFormRenderer,BrowsableAPIRenderer ] def get(self,request,pk): book_obj=models.Book.objects.filter(pk=pk).first() bs=BookSerializers(book_obj,many=False) return Response(bs.data) def put(self,request,pk): book_obj = models.Book.objects.filter(pk=pk).first() bs=BookSerializers(data=request.data,instance=book_obj) if bs.is_valid(): bs.save() # update return Response(bs.data) else: return Response(bs.errors) def delete(self,request,pk): models.Book.objects.filter(pk=pk).delete() return Response("")
-
全局响应器
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES':['rest_framework.renderers.JSONRenderer'] }
-
自定义显示模板(不推荐)
from rest_framework.renderers import TemplateHTMLRenderer class BookDetailView(APIView): renderer_classes = [TemplateHTMLRenderer] def get(self,request,pk): book_obj=models.Book.objects.filter(pk=pk).first() bs=BookSerializers(book_obj,many=False) return Response(bs.data,template_name='aa.html')
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ title }} {{ publishDate }} </body> </html>