rest-framework之权限组件

时间:2021-01-25 20:37:49

权限

权限

作用 : 校验用户是否有权限访问

  • 检测权限肯定是在用户认证通过之后,所有可以直接在request中取出用户做判断
  • 先定义一个类,继承 BasePermission.
from rest_framework.permissions import BasePermission
class myPermission(BasePermission):
#权限认证失败的提示信息....
message = '不是超超级用户,查看不了'
def has_permission(self, request, view):
if request.user.usertyle != 3:
return False
else:
return True
  • 局部使用:只需要在视图类中加入
permission_classes=[myPermission,]
  • 全局使用 setting中设置 导入自己创建的类的函数的位置
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES": ["app01.service.auth.Authentication",],
"DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",]
}

权限类使用顺序

权限类使用顺序:先用视图类中的权限类,再用settings里配置的权限类,最后用默认的权限类

局部使用例子

  1. models 层
class User(models.Model):
username=models.CharField(max_length=32)
password=models.CharField(max_length=32)
user_type=models.IntegerField(choices=((1,'超级用户'),(2,'普通用户'),(3,'二笔用户'))) class UserToken(models.Model):
user=models.OneToOneField(to='User')
token=models.CharField(max_length=64)
  1. 新建认证类(验证通过return两个参数)
from rest_framework.permissions import BasePermission
class myPermission(BasePermission):
message = '不是超超级用户,查看不了'
def has_permission(self, request, view):
#检测是否有权限
if request.user.usertyle != 3:
return False
else:
return True
  1. view层
from app01.auth import myAuthen
from app01.auth import myPermission class Book(APIView):
authentication_classes = [myAuthen, ]
permission_classes=[myPermission,] def get(self, request):
response = MyResponse() print(request.user.name)
print(request.auth.token)
# 必须登陆才能访问
books = models.Book.objects.all()
ret = myserial.BookSer(instance=books, many=True)
response.msg = '查询成功'
response.data = ret.data
return JsonResponse(response.get_dic, safe=False)

第二个例子

from rest_framework.permissions import BasePermission
class UserPermission(BasePermission):
message = '不是超级用户,查看不了'
def has_permission(self, request, view):
# user_type = request.user.get_user_type_display()
# if user_type == '超级用户':
user_type = request.user.user_type
print(user_type)
if user_type == 1:
return True
else:
return False
class Course(APIView):
authentication_classes = [TokenAuth, ]
permission_classes = [UserPermission,] def get(self, request):
return HttpResponse('get') def post(self, request):
return HttpResponse('post')

全局使用 在setting中添加

REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],
"DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",]
}

源码分析

def check_permissions(self, request):
for permission in self.get_permissions():
if not permission.has_permission(request, self):
self.permission_denied(
request, message=getattr(permission, 'message', None)
)

self.get_permissions()

def get_permissions(self):
return [permission() for permission in self.permission_classes]

大帅逼的链接