澳门至尊网站-首页

您的位置:澳门至尊网站 > 技术教程 > 权限组件源码分析

权限组件源码分析

2019-11-14 17:21

在上风华正茂篇小说中大家早就解析了认证组件源码,大家再来看看权限组件的源码,权限组件相对轻便,因为只供给回到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卡塔 尔(英语:State of Qatar)中的权限决断文件(permision.py卡塔 尔(英语:State of Qatar)中去。

  图片 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

 

 默许是未有任何逻辑决断的,所以大家在自定义权限类的时候,得投机写那五个措施。

 其余说美素佳儿(Friso卡塔 尔(阿拉伯语:قطر‎下底下那一个作案的效果  

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'],
}

 

本文由澳门至尊网站发布于技术教程,转载请注明出处:权限组件源码分析

关键词: