源碼過程分析
由於CBV中,請求是先從dispatch()方法進去,我們像第一篇中研究認證一樣,先看dispatch()的源碼
def dispatch(self, request, *args, **kwargs):
"""
`.dispatch()` is pretty much the same as Django's regular dispatch,
but with extra hooks for startup, finalize, and exception handling.
"""
self.args = args
self.kwargs = kwargs
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
self.initial(request, *args, **kwargs)
# Get the appropriate handler method
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
response = handler(request, *args, **kwargs)
except Exception as exc:
response = self.handle_exception(exc)
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
上一篇講過,先封裝request,然後執行initial()方法,initial()源碼如下
def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs)
# Perform content negotiation and store the accepted info on the request
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg
# Determine the API version, if versioning is in use.
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
# Ensure that the incoming request is permitted
self.perform_authentication(request)
'''執行完認證,開始進行權限'''
self.check_permissions(request)
self.check_throttles(request)
點擊check_permissions
進去查看源碼
def check_permissions(self, request):
"""
Check if the request should be permitted.
Raises an appropriate exception if the request is not permitted.
"""
"""
循環權限類的實例列表,調用權限類的has_permission方法,
如果has_permission方法返回True,則認證成功。
返回False就是認證失敗,拋出異常
"""
for permission in self.get_permissions():
if not permission.has_permission(request, self):
"""
這裏是從'message'裏面拿異常信息,
我們可以在我們的類裏面自己寫message,從而實現自定義
"""
self.permission_denied(
request, message=getattr(permission, 'message', None)
)
接下來點進去看get_permissions()
方法,其實從上一篇中大概也可以猜到,這裏應該是使用列表生成式生成一個對象列表。
def get_permissions(self):
"""
Instantiates and returns the list of permissions that this view requires.
"""
# 實例化permission_classes裏的類,返回一個實例化的permisson列表
return [permission() for permission in self.permission_classes]
然後我們再點進去源碼看看permission_classes
裏面是啥,
permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
可以看到如果我們自己重寫了permission_classes
,就用我們自己的,我們自己沒有寫就用Django rest framework的。
接下來點進去api_settings
api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)
然後還是像研究認證過程的源碼一樣,點DEFAULTS
看看源碼,看它默認的DEFAULT_PERMISSION_CLASSES
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
],
用法
- 創建一個類,必須繼承:
BasePermission
,必須實現:has_permission
方法
from rest_framework.permissions import BasePermission
class SVIPPermission(BasePermission):
message = "必須是SVIP才能訪問" # 這個信息postman會輸出
def has_permission(self,request,view):
if request.user.user_type != 3:
return False
return True
- 返回值:
- True, 有權訪問
- False,無權訪問
- 權限局部使用
class UserInfoView(APIView):
"""
訂單相關業務(普通用戶、VIP)
"""
permission_classes = [MyPermission1, ]
def get(self,request,*args,**kwargs):
return HttpResponse('用戶信息')
- 權限全局使用
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES":['api.utils.permission.SVIPPermission']
}