DRF权限控制
DRF权限控制
前提:你的用户表中需要有权限的字段,下面的权限的字段是user_type
1.写一个权限控制类
from rest_framework import exceptions
from app01 import models
from rest_framework.permissions import BasePermission
class Userpermission(Basepermission):
#使放回的错误信息变成你想显示的信息
massage = '您没有权限!'
#注意这里的方法名固定
def has_permission(self, request, view):
user_type = request.user.user_type
if user_type == 2:
#返回True表示验证通过
return True
else:
#返回False表示验证不通过
return False
2.局部使用
在视图类中添加
permission_classes = [AuthAPI.UserPermission,]
例如:
class Books(APIView):
permission_classes = [AuthAPI.UserPermission,]
def get(self, request):
books = models.Book.objects.all()
books_res = BooksDRF(books, many=True)
authors = models.Author.objects.all()
authors_res = AuthorsDRF(instance=authors,many=True)
response = {'status':200,'msg':'查询成功!','books':books_res.data,'authors':authors_res.data}
return JsonResponse(response, safe=False)
3.全局使用
在setting中配置
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ['app01.AuthAPI.UserPermission']
}
4.局部禁用(与全局使用配合使用)
在要禁用的视图函数中添加
permission_classes = []
例如:
class Books(APIView):
permission_classes = []
def get(self, request):
books = models.Book.objects.all()
books_res = BooksDRF(books, many=True)
authors = models.Author.objects.all()
authors_res = AuthorsDRF(instance=authors,many=True)
response = {'status':200,'msg':'查询成功!','books':books_res.data,'authors':authors_res.data}
return JsonResponse(response, safe=False)