权限组件源码分析

在上一篇文章中我们已经分析了认证组件源码,我们再来看看权限组件的源码,权限组件相对容易,因为只需要返回True
和False即可

基本代码结构

  url.py:

from django.conf.urls import url, includefrom app import views  urlpatterns = [    url(r'^test/', views.TestView.as_view,]

  views.py:

from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.request import Requestfrom rest_framework import exceptions  class MyPermission:    def has_permission(request, self):    '''    权限代码编写区域    '''    return True  #权限通过 如果权限不通过 返回False   class TestView:    permission_classes = [MyPermission, ]      def get(self, request, *args, **kwargs):        pass           def post(self, request, *args, **kwargs):        pass         '''        等等一系列的视图功能方法        '''

代码

  说明:

    • has_permission方法的返回值是布尔类型,True表示权限通过,False表示权限拒绝
    • 上面的基本结构是做局部的类的权限判断方式,全局权限判断后文介绍。
    • permission_classes属性变量同样也是一个列表,列表元素是权限判断类。

图片 1图片 2

源码分析

  其实权限的源码流程跟认证的流程基本相同。还是要抓住通过源码要想知道什么,不然就会陷入浩如烟海的源码之中。

 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 视图类

– 为什么会使用permission_classes属性变量?

 
图片 3

  python
的面向对象编程中,我们首先要执行的方法肯定是dispatch方法,所以我们的分析入口就是dispatch方法,在dispatch方法中,可以看到,通过initialize_request方法将django原生的request进行了一次封装。由initialize_request方法的实现过程可以看出,将其封装实例化成了一个Request对象。但权限判断并没有像认证一样初始化到了Request对象中,但对django原生的request封装还是需要强调的,因为编写代码的过程中对django原生的request的使用是必不可免的。

 
图片 4

 
同样的,权限判断的具体过程跟认证一样,也是在dispatch方法中所调用的initial方法中实现。再跳转到initial方法中去。

 
图片 5

 
在initial方法中,可以看到权限判断的方法,没错,就是通过check_permissions方法实现的。再跳转到这个方法中去。

 
图片 6

在check_permissions方法中,就可以看到权限的判断就是通过这个for循环实现的。正因为在业务代码中可能存在若干种类型的权限判断,所以才会通过循环去执行我们定义好的权限判断类来完成多个权限体系的判断功能。这样,我们可以感觉到这里的“self.get_permissions()”的返回值应该就是我们在视图类中赋值过的permissions_classes属性变量的值。那就跳转到这个方法中去看看吧。

  图片 7

  在get_permissions方法中看到,跟认证一样,返回值同样是一个列表生成式,而这个列表生成式使用的属性变量正是我们赋值过的permission_classes,跟我们之前的猜测完全一致。综上所述,我们为了让drf接口源码使用上我们自己定义的权限判断类,那我们就必须按照源码中写的借口,将permission_classes属性变量赋值

视图类

– 在权限判断类中为什么会定义一个名称为has_permission的方法?

  图片 8

  回到check_permissions方法中,我们看if判断句,前面刚刚说过,在for中的permission其实就是我们自己定义的权限判断类,那么在if句中的“.has_permission(request,self)”不就应该就是Mypermission类中的方法吗?所以,我们自己定义的Mypermission类中一定要实现has_permission这个方法。(要注意这个方法的参数)    

图片 9图片 10

– has_permission方法中,为什么返回值为布尔值?

  还是跟上一个问题一样的,在上图中的if句中,我们可以看到“permission.has_permission(request,
self)”的返回值不就是布尔值吗,这个返回值不就是has_permission方法返回值吗?当返回值为False时,就会执行if句中的代码,来抛出异常。

  图片 11

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

实例

图片 12图片 13

from django.conf.urls import url, includefrom web.views import TestViewurlpatterns = [    url(r'^test/', TestView.as_view,]

urls.py图片 14图片 15

#!/usr/bin/env python# -*- coding:utf-8 -*-from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.authentication import BaseAuthenticationfrom rest_framework.permissions import BasePermissionfrom rest_framework.request import Requestfrom rest_framework import exceptionstoken_list = [    'sfsfss123kuf3j123',    'asijnfowerkkf9812',]class TestAuthentication(BaseAuthentication):    def authenticate(self, request):        """        用户认证,如果验证成功后返回元组: (用户,用户Token)        :param request:         :return:             None,表示跳过该验证;                如果跳过了所有认证,默认用户和Token和使用配置文件进行设置                self._authenticator = None                if api_settings.UNAUTHENTICATED_USER:                    self.user = api_settings.UNAUTHENTICATED_USER() # 默认值为:匿名用户                else:                    self.user = None                        if api_settings.UNAUTHENTICATED_TOKEN:                    self.auth = api_settings.UNAUTHENTICATED_TOKEN()# 默认值为:None                else:                    self.auth = None            (user,token)表示验证通过并设置用户名和Token;            AuthenticationFailed异常        """        val = request.query_params.get('token')        if val not in token_list:            raise exceptions.AuthenticationFailed("用户认证失败")        return ('登录用户', '用户token')    def authenticate_header(self, request):        """        Return a string to be used as the value of the `WWW-Authenticate`        header in a `401 Unauthenticated` response, or `None` if the        authentication scheme should return `403 Permission Denied` responses.        """        passclass TestPermission(BasePermission):    message = "权限验证失败"    def has_permission(self, request, view):        """        判断是否有权限访问当前请求        Return `True` if permission is granted, `False` otherwise.        :param request:         :param view:         :return: True有权限;False无权限        """        if request.user == "管理员":            return True    # GenericAPIView中get_object时调用    def has_object_permission(self, request, view, obj):        """        视图继承GenericAPIView,并在其中使用get_object时获取对象时,触发单独对象权限验证        Return `True` if permission is granted, `False` otherwise.        :param request:         :param view:         :param obj:         :return: True有权限;False无权限        """        if request.user == "管理员":            return Trueclass TestView:    # 认证的动作是由request.user触发    authentication_classes = [TestAuthentication, ]    # 权限    # 循环执行所有的权限    permission_classes = [TestPermission, ]    def get(self, request, *args, **kwargs):        # self.dispatch        print(request.user)        print(request.auth)        return Response('GET请求,响应内容')    def post(self, request, *args, **kwargs):        return Response('POST请求,响应内容')    def put(self, request, *args, **kwargs):        return Response('PUT请求,响应内容')

views.py

自定义权限类

扩展:全局权限

  同样,跟全局认证一样,我们只需要在settings配置文件中添加配置项即可。然后,我们仍然需要将我们自定义的权限类也写到我们在跟views.py同级目录下新建的文件夹(我习惯叫utils)中的权限判断文件(permision.py)中去。

  图片 16

REST_FRAMEWORK = {    "DEFAULT_PERMISSION_CLASSES" :['api.utils.permission.Mypermission',]    }

  Mypermission就是我们写在utils文件夹中permission.py文件中的一个权限类。

  注意:如果有部分类不需要权限判断的话,可以在Mypermission类中添加“permission_classes
= []
”,即可。 

图片 17图片 18

urlpatterns = [
    url(r'^payment/$', payment.PaymentView.as_view({'post': 'create','put': 'update','get':'list'})),
]

路由

跟上一篇一样,来看代码是如何走到我自定义的权限类中的。

1.首先从url中分析

  1.先来到视图类中的as.view()方法

  图片 19

  而我们的自定义的方法中没有as.view()方法,那就要去父类ViewSetMixin和APIView中去找,好看源码

2.分析源码

  1.先看ViewSetMixin类中

    图片 20

    

图片 21

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)

图片 22

 

   2.找dispatch方法在哪里,答案肯定是在APIView中

  

图片 23

 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

图片 24

 

    所有的关键点都在dispatch方法里面:

    (1)  request = self.initialize_request(request, *args,
**kwargs) 

      

图片 25

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

    图片 26

    这里默认去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'],
}

 

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*
*
Website