一、分页器(三种)如何使用
1、内置了三种分页器
PageNumberPagination:普通分页
LimitOffsetPagination:偏移分页
CursorPagination:游标分页
2、使用
from rest_framework.viewsets import ViewSetMixin,GenericViewSet
from rest_framework.mixins import ListModelMixin
from app01 import models,serializer
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPagination
#PageNumberPagination:普通分页(用的最多)
class MyPageNumberPagination(PageNumberPagination):
page_size = 4 # 每页显示多少条
page_query_param = 'page' # 查询参数
page_size_query_param = 'size' # 查询的时候指定每页显示多少条
max_page_size = 5 # 每页最多显示多少条
’‘’
-使用方式:
-定义一个类,继承PageNumberPagination
-重写四个属性
-在继承了GenericAPIView+ListModelMixin视图类中配置
pagination_class = MyPageNumberPagination
-查询
http://127.0.0.1:8000/students/?page=1&size=5
‘’‘
#偏移分页
class MyLimitOffsetPagination(LimitOffsetPagination):
default_limit = 2 # 默认条数
limit_query_param = 'limit' # 查询时,指定查询多少条
offset_query_param = 'offset' # 查询时,指定的起始位置是哪
max_limit = None # 查询时,最多返回多少条
’‘’
-使用方式:
-定义一个类,继承LimitOffsetPagination
-重写四个属性
-在继承了GenericAPIView+ListModelMixin视图类中配置
pagination_class = MyPageNumberPagination
-查询
http://127.0.0.1:8000/students/?limit=100&offset=1
‘’‘
#游标分页(速度快)
class MyCursorPagination(CursorPagination):
cursor_query_param = 'cursor' # 查询的时候,指定的查询方式
page_size = 2 # 每页显示多少条
ordering = 'id' # 排序方式
# page_size_query_param = 'size' # 查询的时候指定每页显示多少条
# max_page_size = None # 每页最多显示多少条
’‘’
http://127.0.0.1:8000/students/?cursor 只能上下查询
‘’‘
class StudentView(GenericViewSet,ListModelMixin):
queryset = models.Student.objects.all()
serializer_class = serializer.Studentserializer
pagination_class = MyPageNumberPagination
# pagination_class = MyLimitOffsetPagination
# pagination_class = MyCursorPagination
3、APIView的分页模式
#新建一个类,继承普通分页,重写四个属性
from rest_framework.views import APIView
class StudentApiView(APIView):
def get(self,request):
student_list = models.Student.objects.all()
page = MyPageNumberPagination() #实例化得到对象,只需要换不同的分页类即可
res = page.paginate_queryset(student_list,request,self) #开始分页
ser = serializer.Studentserializer(res,many=True)
return page.get_paginated_response(ser.data)
二、全局异常的捕获
1、统一接口的返回方式,即便视图函数执行出错
2、使用方式
#写一个函数
from rest_framework.views import exception_handler
from rest_framework import status
def common_exception_handler(exc, context):
response = exception_handler(exc, context)
if response is None:
response = Response({'code':999,'detail': '未知错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return response
#在settings中配置
REST_FRAMEWORK = {
'EXCEPTION_HANDLER':'app01.utils.common_exception_handler'
}
3、通常情况下会记录日志
-使用django日志记录 ,xx.log文件中
-使用sentry(公司自己写)日志记录,平台(django),查询,统计,告警
三、封装Response对象
#自定义一个类,继承Response
from rest_framework.response import Response
class APIResponse(Response):
def __init__(self,code=100,msg='成功',data=None,status=None,headers=None,content_type=None,**kwargs):
dic = {'code':code,'msg':msg}
if data:
dic['data'] = data
dic.update(kwargs)
super().__init__(data=dic,status = status,template_name=None,headers=headers,exception=False,content_type=content_type)
#使用
from rest_framework.views import APIView
from app01 import util
class StudentApiView(APIView):
def get(self,request):
student_list = models.Student.objects.all()
# page = MyPageNumberPagination()
# res = page.paginate_queryset(student_list,request,self)
# ser = serializer.Studentserializer(res,many=True)
# return page.get_paginated_response(ser.data)
ser = serializer.Studentserializer(student_list,many = True)
return util.APIResponse(code=100,msg='查询成功',data=ser.data,count=200,next='https://wwww.dand.com')
四、自动生成接口文档
1、借助于第三方:coreapi、swagger
2、在路由中
from rest_framework.documentation import include_docs_urls
path('docs/',include_docs_urls(title='图书管理系统api'))
3、在配置文件中
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
4、写视图类(需要加注释)
class BookListCreateView(ListCreateAPIView):
"""
get:
返回所有图书信息.
asdfasfda
post:
新建图书.
"""
queryset = Student.objects.all()
serializer_class = StudentSerializer
5、只需要在浏览器输入,就可以看到自动生成的接口文档
http://127.0.0.1:8000/docs/
注:在settings中注册rest_framework