权限
写一个类,继承BasePermission,如果通过返回True,否则False
这里需要配合认证使用,否则没有user_type属性。
from rest_framework.permissions import BasePermissionclass UserPermission(BasePermission):def has_permission(self, request, view):# 不是超级用户不能访问# 如果认证已经通过了, request 内勇敢有user对象。# 当前登录用户user = request.userif user.user_type == 1:return Trueelse:return False
局部使用
在视图类添加
class TestView(APIView):permission_classes = [app_auth.UserPermission]
全局使用
在配置文件添加
REST_FRAMEWORK={'DEFAULT_PERMISSION_CLASSES':['app_authentication.app_auth.UserPermission',]
}
局部禁用
class TestView(APIView):permission_classes = []
内置频率
全局配置
未登录用户限制
REST_FRAMEWORK={'DEFAULT_THROTTLE_CLASSES': ('rest_framework.throttling.AnonRateThrottle',),'DEFAULT_THROTTLE_RATES': {'anon': '3/m',}
过滤组件
组件是django的,放在rest framework使用
1.安装
pip install django-filter
2.注册
INSTALLED_APPS = [...'django_filters', # 需要注册应用,
]
3.配置
全局配置为例
REST_FRAMEWORK = {...'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}
from rest_framework.generics import ListAPIView
from app01.models import Book
from app_authentication.ser import BookModelSerializerclass BookView(ListAPIView):queryset = Book.objects.all()serializer_class = BookModelSerializerfilter_fields = ('name', 'price')
访问:http://127.0.0.1:8000/app_authentication/bookview/?price=22.10
排序
from rest_framework.filters import OrderingFilter
class Book2View(ListAPIView):queryset = Book.objects.all()serializer_class = BookModelSerializer# 如果有局部过滤功能,在列表添加filter_backends = [OrderingFilter]ordering_fields=('id','price')
访问:
倒序:http://127.0.0.1:8000/app_authentication/book2view/?ordering=-price
正序:http://127.0.0.1:8000/app_authentication/book2view/?ordering=price
异常处理
1.统一抛出固定格式错误信息
2.记日志
自定义异常方法,替换全局使用
# 自定义异常
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)# response 两种情况# None drf 没有处理# Response 对象,django处理,但不符合需求print(type(exc))if not response: # 非空if isinstance(exc,ZeroDivisionError):return Response(data={'status':777,'msg':'除以0错误'+str(exc)},status=status.HTTP_400_BAD_REQUEST)return Response(data={'status': 999, 'msg': str(exc)}, status=status.HTTP_400_BAD_REQUEST)else:return Response(data={'status': 888, 'msg': response.data.get('detail')}, status=status.HTTP_400_BAD_REQUEST)
settings.py
REST_FRAMEWORK={...'EXCEPTION_HANDLER':'app_authentication.app_auth.my_exception_handler'
}
封装Response对象
class APIResponse(Response):def __init__(self,code=100,msg='成功',data=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=dic,status=status,headers=headers)
使用
from app_authentication.app_auth import APIResponse
class TestView4(APIView):def get(self,request,*args,**kwargs):return APIResponse(data={"nane":'abc'},token="sldjfl",aa="123123")# return APIResponse(data={"nane":'abc'})
# return APIResponse(token="sldjfl",aa="123123")