過濾組件
查詢所有才涉及到過濾,其他介面都不需要
restful規范中有一條,請求地址中帶過濾條件:分頁、排序、過濾統稱為過濾
內置過濾類
使用內置過濾類的步驟
必須是繼承GenericAPIView+ListModelMixin的之類視圖上
1.配置過濾類
filter_backends=[SearchFilter,]
2.配置過濾類的欄位
search_fields = ['name', ]
3.支持前端的訪問形式
http://127.0.0.1:8000/books/?search=三 # 只要name中或publish中有三都能搜出來
內置過濾類只能通過search寫條件,如果配置了多個過濾欄位,是或者的條件

采用第三方過濾組件
#1 安裝:pip3 install django-filter
#2 注冊,在app中注冊django-filter
#3 全域配,或者區域配
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
#4 視圖類
class BookView(ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
filter_fields = ('name',) #配置可以按照哪個欄位來過濾
排序組件
排序功能只針對于所有介面,繼承了GenericAPIView的視圖類,只要加入,倆個類屬性就可以了
from rest_framework.filters import OrderingFilter
# 查詢所有,按照價格排序,必須繼承GenericAPIView及其子類
class BookView(ViewSetMixin, GenericAPIView, ListModelMixin):
queryset = Book.objects.all()
serializer_class = BookSerializer
filter_backends = [OrderingFilter, ]
ordering_fields = ['price',]
訪問地址:
http://127.0.0.1:8000/books/?ordering=-price # 按照price降序
http://127.0.0.1:8000/books/?ordering=price # 按照price升序
http://127.0.0.1:8000/books/?ordering=price,id # 先按價格升序排,價格一樣再按id升序排
注意:
ordering后面跟的必須要在ordering_fields = ['price','id']先注冊好

全域例外處理
用于:統一介面回傳
# 自定義例外方法,替換掉全域
# 寫一個方法
# 自定義例外處理的方法
from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
def my_exception_handler(exc, context):
response=exception_handler(exc, context)
# 兩種情況,一個是None,drf沒有處理
#response物件,django處理了,但是處理的不符合咱們的要求
# print(type(exc))
if not response:
if isinstance(exc, ZeroDivisionError):
return Response(data=https://www.cnblogs.com/suncolor/p/{'status': 777, 'msg': "除以0的錯誤" + str(exc)}, status=status.HTTP_400_BAD_REQUEST)
return Response(data=https://www.cnblogs.com/suncolor/p/{'status':999,'msg':str(exc)},status=status.HTTP_400_BAD_REQUEST)
else:
# return response
return Response(data=https://www.cnblogs.com/suncolor/p/{'status':888,'msg':response.data.get('detail')},status=status.HTTP_400_BAD_REQUEST)
# 全域配置setting.py
'EXCEPTION_HANDLER': 'app01.app_auth.my_exception_handler',
自己封裝的response物件
# 以后都用自己封裝的
class APIResponse(Response):
def __init__(self,code=100,msg='成功',data=https://www.cnblogs.com/suncolor/p/None,status=None,headers=None,**kwargs):
dic = {'code': code, 'msg': msg}
if data:
dic = {'code': code, 'msg': msg,'data':data}
dic.update(kwargs)
super().__init__(data=https://www.cnblogs.com/suncolor/p/dic, status=status,headers=headers)
# 使用
return APIResponse(data=https://www.cnblogs.com/suncolor/p/{"name":'lqz'},token='dsafsdfa',aa='dsafdsafasfdee')
return APIResponse(data=https://www.cnblogs.com/suncolor/p/{"name":'lqz'})
return APIResponse(code='101',msg='錯誤',data=https://www.cnblogs.com/suncolor/p/{"name":'lqz'},token='dsafsdfa',aa='dsafdsafasfdee',header={})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/518712.html
標籤:Python
