一梢睛、分頁器(三種)如何使用
1肥印、內(nèi)置了三種分頁器
PageNumberPagination:普通分頁
LimitOffsetPagination:偏移分頁
CursorPagination:游標(biāo)分頁
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' # 查詢參數(shù)
page_size_query_param = 'size' # 查詢的時(shí)候指定每頁顯示多少條
max_page_size = 5 # 每頁最多顯示多少條
’‘’
-使用方式:
-定義一個(gè)類绝葡,繼承PageNumberPagination
-重寫四個(gè)屬性
-在繼承了GenericAPIView+ListModelMixin視圖類中配置
pagination_class = MyPageNumberPagination
-查詢
http://127.0.0.1:8000/students/?page=1&size=5
‘’‘
#偏移分頁
class MyLimitOffsetPagination(LimitOffsetPagination):
default_limit = 2 # 默認(rèn)條數(shù)
limit_query_param = 'limit' # 查詢時(shí)深碱,指定查詢多少條
offset_query_param = 'offset' # 查詢時(shí),指定的起始位置是哪
max_limit = None # 查詢時(shí)藏畅,最多返回多少條
’‘’
-使用方式:
-定義一個(gè)類敷硅,繼承LimitOffsetPagination
-重寫四個(gè)屬性
-在繼承了GenericAPIView+ListModelMixin視圖類中配置
pagination_class = MyPageNumberPagination
-查詢
http://127.0.0.1:8000/students/?limit=100&offset=1
‘’‘
#游標(biāo)分頁(速度快)
class MyCursorPagination(CursorPagination):
cursor_query_param = 'cursor' # 查詢的時(shí)候,指定的查詢方式
page_size = 2 # 每頁顯示多少條
ordering = 'id' # 排序方式
# page_size_query_param = 'size' # 查詢的時(shí)候指定每頁顯示多少條
# 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的分頁模式
#新建一個(gè)類绞蹦,繼承普通分頁力奋,重寫四個(gè)屬性
from rest_framework.views import APIView
class StudentApiView(APIView):
def get(self,request):
student_list = models.Student.objects.all()
page = MyPageNumberPagination() #實(shí)例化得到對(duì)象,只需要換不同的分頁類即可
res = page.paginate_queryset(student_list,request,self) #開始分頁
ser = serializer.Studentserializer(res,many=True)
return page.get_paginated_response(ser.data)
二幽七、全局異常的捕獲
1景殷、統(tǒng)一接口的返回方式,即便視圖函數(shù)執(zhí)行出錯(cuò)
2锉走、使用方式
#寫一個(gè)函數(shù)
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': '未知錯(cuò)誤'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return response
#在settings中配置
REST_FRAMEWORK = {
'EXCEPTION_HANDLER':'app01.utils.common_exception_handler'
}
3滨彻、通常情況下會(huì)記錄日志
-使用django日志記錄 ,xx.log文件中
-使用sentry(公司自己寫)日志記錄挪蹭,平臺(tái)(django)亭饵,查詢,統(tǒng)計(jì)梁厉,告警
三辜羊、封裝Response對(duì)象
#自定義一個(gè)類,繼承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')
四词顾、自動(dòng)生成接口文檔
1八秃、借助于第三方:coreapi、swagger
2肉盹、在路由中
from rest_framework.documentation import include_docs_urls
path('docs/',include_docs_urls(title='圖書管理系統(tǒng)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上忍、只需要在瀏覽器輸入骤肛,就可以看到自動(dòng)生成的接口文檔
http://127.0.0.1:8000/docs/
注:在settings中注冊(cè)rest_framework