1.自带的权限验证
系统自带权限认证类:
1) AllowAny: 允许所有用户,校验方法直接返回True
2) IsAuthenticated: 只允许登陆用户访问 reqest.user and request.user.is_authenticated
3) IsAuthenticatedOrReadOnly: 游客只读,登陆用户无限制 get、option、head请求无限制
4) IsAdminUser: 是否是后台用户 校验request.user和request.user.is_staff(可以登陆后台管理系统的用户)
5) 以上4个类都可以通过from rest_framework.permission import 导出来点进去看源码的权限规制
2.自定义权限验证
继承BasePermission类 重写has_permission方法
from rest_framework.permission import BasePermissionclass IsAdminUser(BasePermission):def has_permission(self, request, view):user = request.userif not user:return False# 查询用户在group表中所在的组是否为1if user.group.filter(group_id=1):return Truereturn False
在settings中配置
REST_FRAMEWORK = {'DEFAULT_PERMISSION_CLASSES': [# 系统的权限规则'rest_framework.permissions.IsAuthenticatedOrReadOnly',# 自定义的权限规则'utils.permissions.IsAdminUser'}
view中配置
from utils.permissions import IsAdminUserfrom rest_framework.view improt APIViewfrom rest_framework.response import Responseclass TestView(APIView):permission_classes = [IsAdminUser]def post(self, request, *args, **kwargs):return Response('success')
