REST framework 权限管理源码分析
REST framework 權(quán)限管理源碼分析
同認(rèn)證一樣,dispatch()作為入口,從self.initial(request, *args, **kwargs)進(jìn)入initial()
def initial(self, request, *args, **kwargs):# .......# 用戶認(rèn)證self.perform_authentication(request)# 權(quán)限控制self.check_permissions(request)# ...check_permissions()便是權(quán)限管理源碼的入口
# 權(quán)限管理def check_permissions(self, request):"""Check if the request should be permitted.Raises an appropriate exception if the request is not permitted."""for permission in self.get_permissions():if not permission.has_permission(request, self):self.permission_denied(request, message=getattr(permission, 'message', None))和用戶認(rèn)證一樣,同樣遍歷一個(gè)權(quán)限類(lèi)對(duì)象列表,并且調(diào)用該列表中元素的has_permission()方法,該方法返回布爾值,True代表有權(quán)限,False代表沒(méi)有權(quán)限.
def get_permissions(self):return [permission() for permission in self.permission_classes]如果沒(méi)有權(quán)限,就調(diào)用permission_denied()
def permission_denied(self, request, message=None):if request.authenticators and not request.successful_authenticator:raise exceptions.NotAuthenticated()raise exceptions.PermissionDenied(detail=message)如果使用了REST的認(rèn)證框架(authentication_classes數(shù)組不為空)并且身份認(rèn)證失敗,就拋出NotAuthenticated異常,否則會(huì)拋出PermissionDenied異常
class NotAuthenticated(APIException):status_code = status.HTTP_401_UNAUTHORIZEDdefault_detail = _('Authentication credentials were not provided.')default_code = 'not_authenticated'NotAuthenticated會(huì)導(dǎo)致一個(gè)401錯(cuò)誤(缺少用戶憑證)
class PermissionDenied(APIException):status_code = status.HTTP_403_FORBIDDENdefault_detail = _('You do not have permission to perform this action.')default_code = 'permission_denied'而PermissionDenied會(huì)返回錯(cuò)誤403(拒絕授權(quán)訪問(wèn))
在向permission_denied()類(lèi)傳遞參數(shù)時(shí),使用了反射
self.permission_denied(request, message=getattr(permission, 'message', None))會(huì)在這個(gè)權(quán)限類(lèi)對(duì)象中尋找message屬性,沒(méi)找到就使用None,而這個(gè)參數(shù)在后來(lái)只會(huì)被用在PermissionDenied異常上,這些異常都繼承自APIException,而在APIException的構(gòu)造器中,可以發(fā)現(xiàn)detail參數(shù)就是異常描述,而在自己的權(quán)限類(lèi)中定義message屬性可以改變認(rèn)證失敗后的描述
class APIException(Exception):status_code = status.HTTP_500_INTERNAL_SERVER_ERRORdefault_detail = _('A server error occurred.')default_code = 'error'def __init__(self, detail=None, code=None):if detail is None:detail = self.default_detailif code is None:code = self.default_code# ...示例
# api/utils/Permission.py from rest_framework.permissions import BasePermissionclass CommonPermission(BasePermission):"""普通用戶權(quán)限,作用于全局"""def has_permission(self, request, view):print(request.user)if request.user.user_type == 1:return Truedef has_object_permission(self, request, view, obj):"""一旦獲得View權(quán)限,將獲得所有object權(quán)限:return: True"""return Trueclass VipPermission(BasePermission):"""VIP 用戶權(quán)限"""message = '您首先要稱為VIP才能訪問(wèn)'def has_permission(self, request, view):print(request.user)if request.user.user_type == 2:return Truedef has_object_permission(self, request, view, obj):return True # api/view.py from django.shortcuts import HttpResponse from django.http import JsonResponse from rest_framework.views import APIView from api.utils.Permission import VipPermissionclass LoginView(APIView):authentication_classes = []# 登錄無(wú)需權(quán)限認(rèn)證permission_classes = []def post(self, request, *args, **kwargs):pass@method_decorator(csrf_exempt, name='dispatch') class ShopView(APIView):def get(self, request, *args, **kwargs):return HttpResponse(request.user.username)def post(self, request, *args, **kwargs):return HttpResponse('POST')class VipIndexView(APIView):"""只授權(quán)給VIP用戶查看"""permission_classes = [VipPermission]def get(self, *args, **kwargs):return JsonResponse("welcome VIP ", safe=False) # RESTdemo.setting.py REST_FRAMEWORK = {'DEFAULT_AUTHENTICATION_CLASSES': ['api.utils.MyAuthentication.MyAuthentication'],'UNAUTHENTICATED_USER': None,'UNAUTHENTICATED_TOKEN': None,'DEFAULT_PERMISSION_CLASSES': ['api.utils.Permission.CommonPermission'] }總結(jié)
以上是生活随笔為你收集整理的REST framework 权限管理源码分析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Linux安装vim命令
- 下一篇: ddrelease64 黑苹果_GitH