Django REST framework —— 權限組件源碼分析
阿新 • • 發佈:2018-08-20
show lis 列表 登錄用戶 必須 分享圖片 exception map 這一
在上一篇文章中我們已經分析了認證組件源碼,我們再來看看權限組件的源碼,權限組件相對容易,因為只需要返回True 和False即可
代碼
1 class ShoppingCarView(ViewSetMixin, APIView): 2 permission_classes = [MyPermission, ] 3 def list(self,request, *args, **kwargs): 4 """ 5 查看購物車信息 6 :param args: 7 :param kwargs:視圖類8 :return: 9 """ 10 try: 11 ret = BaseResponse() 12 pay_course_list = [] 13 # key = ‘shoppingcar_%s_%s‘ % (USERID, ‘*‘) 14 key = settings.SHOPCAR_FORMAT.format( request.user.id, "*") 15 user_key_list = COON.keys(pattern=key) #取到這個用戶對應的所有課程字典 對應的鍵 16 for key in user_key_list: 17 # 對應的每個鍵值 去取每個課程對應的信息 和價格列表 18 temp = { 19 ‘id‘: COON.hget(key, ‘id‘).decode(‘utf8‘), 20 ‘name‘: COON.hget(key, ‘name‘).decode(‘utf8‘), 21 ‘img‘: COON.hget(key, ‘img‘).decode(‘utf8‘), 22 ‘default‘: COON.hget(key, ‘default‘).decode(‘utf8‘), 23 ‘price_dict‘: json.loads(COON.hget(key, ‘price_dict‘).decode(‘utf8‘)), 24 } 25 pay_course_list.append(temp) 26 ret.data = pay_course_list 27 except Exception as e: 28 ret.data = ‘查看失敗‘ 29 ret.code = 00000 30 return Response(ret.dict) 31 32 視圖類
class MyPermission(BasePermission): message = ‘VIP用戶才能訪問‘ def has_permission(self, request, view): """ 自定義權限只有VIP用戶才能訪問 """ # 因為在進行權限判斷之前已經做了認證判斷,所以這裏可以直接拿到request.user if request.user and request.user.type == 2: # 如果是VIP用戶 return True else: return False自定義權限類
urlpatterns = [ url(r‘^payment/$‘, payment.PaymentView.as_view({‘post‘: ‘create‘,‘put‘: ‘update‘,‘get‘:‘list‘})), ]路由
跟上一篇一樣,來看代碼是如何走到我自定義的權限類中的。
1.首先從url中分析
1.先來到視圖類中的as.view()方法
而我們的自定義的方法中沒有as.view()方法,那就要去父類ViewSetMixin和APIView中去找,好看源碼
2.分析源碼
1.先看ViewSetMixin類中
class ViewSetMixin(object): """ This is the magic. Overrides `.as_view()` so that it takes an `actions` keyword that performs the binding of HTTP methods to actions on the Resource. For example, to create a concrete view binding the ‘GET‘ and ‘POST‘ methods to the ‘list‘ and ‘create‘ actions... view = MyViewSet.as_view({‘get‘: ‘list‘, ‘post‘: ‘create‘}) """ @classonlymethod def as_view(cls, actions=None, **initkwargs): """ Because of the way class based views create a closure around the instantiated view, we need to totally reimplement `.as_view`, and slightly modify the view function that is created and returned. """ # The suffix initkwarg is reserved for displaying the viewset type. # eg. ‘List‘ or ‘Instance‘. cls.suffix = None # The detail initkwarg is reserved for introspecting the viewset type. cls.detail = None # Setting a basename allows a view to reverse its action urls. This # value is provided by the router through the initkwargs. cls.basename = None # actions must not be empty if not actions: raise TypeError("The `actions` argument must be provided when " "calling `.as_view()` on a ViewSet. For example " "`.as_view({‘get‘: ‘list‘})`") # sanitize keyword arguments for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don‘t do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r" % ( cls.__name__, key)) def view(request, *args, **kwargs): self = cls(**initkwargs) # We also store the mapping of request methods to actions, # so that we can later set the action attribute. # eg. `self.action = ‘list‘` on an incoming GET request. self.action_map = actions # Bind methods to actions # This is the bit that‘s different to a standard view for method, action in actions.items(): handler = getattr(self, action) setattr(self, method, handler) if hasattr(self, ‘get‘) and not hasattr(self, ‘head‘): self.head = self.get self.request = request self.args = args self.kwargs = kwargs # And continue as usual
# 前面都是在對傳參做判斷和重新賦值,重要的是下面這一步,最後return 調用了dispatch方法
return self.dispatch(request, *args, **kwargs)
2.找dispatch方法在哪裏,答案肯定是在APIView中
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)
## request = Request(.....) self.request = request self.headers = self.default_response_headers 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
所有的關鍵點都在dispatch方法裏面:
(1) request = self.initialize_request(request, *args, **kwargs)
def initialize_request(self, request, *args, **kwargs): """ Returns the initial request object. """ parser_context = self.get_parser_context(request) return Request( request, parsers=self.get_parsers(), authenticators=self.get_authenticators(), #[BasicAuthentication(),],把對象封裝到request裏面了 negotiator=self.get_content_negotiator(), parser_context=parser_context )
(2) self.initial(request, *args, **kwargs)
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)
(3)self.check_permissions(request)
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) )
(4)self.get_permissions():
def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ return [permission() for permission in self.permission_classes] 列表生成式,把自定義的權限類的對象,放在一個對象中
(5)self.permission_classes
這裏默認去settings全局中去找,如果局部配置了靜態變量,就直接去找局部的靜態變量
(6)在看看我們繼承的BasePermission
class BasePermission(object): """ A base class from which all permission classes should inherit. """ def has_permission(self, request, view): """ Return `True` if permission is granted, `False` otherwise. """ return True def has_object_permission(self, request, view, obj): """ Return `True` if permission is granted, `False` otherwise. """ return True
默認是沒有任何邏輯判斷的,所以我們在自定義權限類的時候,得自己寫這兩個方法。
另外說明一下下面這個犯法的作用
def has_object_permission(self, request, view, obj):
"""
Return `True` if permission is granted, `False` otherwise.
"""
return True
對當前登錄用戶做些判斷
def has_object_permission(self, request, view, obj): """ 判斷當前評論用戶的作者是不是你當前的用戶 只有評論的作者才能刪除自己的評論 """ print(‘這是在自定義權限類中的has_object_permission‘) print(obj.id) if request.method in [‘PUT‘, ‘DELETE‘]: if obj.user == request.user: # 當前要刪除的評論的作者就是當前登陸的用戶 return True else: return False else: return True
總結:
(1)使用
- 自己寫的權限類:1.必須繼承BasePermission類; 2.必須實現:has_permission方法
(2)返回值
- True 有權訪問
- False 無權訪問
(3)局部
- permission_classes = [MyPremission,]
(4)全局
REST_FRAMEWORK = { #權限 "DEFAULT_PERMISSION_CLASSES":[‘API.utils.permission.SVIPPremission‘], }
Django REST framework —— 權限組件源碼分析