[1127 | Day67] local and global configuration rights component configuration (source code analysis)

A local authority assembly configuration

1, a request come, first enter the urls.pyfile

url(r'^book_cbv/', views.Book_cbv.as_view(),name="test3"),

2, enter Book_cbvthe class, look for as_viewthe method, this class is the definition of our own, we simply do not write as_view method

class Book_cbv(APIView):
 
    def get(self,request):
        query_list = models.Book.objects.all()
        # bs = book_serializers(query_list,many=True)
        bs = bookmodelserializer(query_list,many=True,context={'request': request})
 
 
        return Response(bs.data)
    def post(self,request):
        bs = bookmodelserializer(data=request.data)
        print(request.data)
        if bs.is_valid():
            print(bs.validated_data)
            bs.save()
            return Response(bs.data)
        else:
            return Response(bs.errors)

3, into the parent Looking as_view method, the parent class APIView, as_view parent class is actually performed APIView class the parent class's viewmethods

@classmethod
def as_view(cls, **initkwargs):
    """
    Store the original class on the view function.
 
    This allows us to discover information about the view when we do URL
    reverse lookups.  Used for breadcrumb generation.
    """
    if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
        def force_evaluation():
            raise RuntimeError(
                'Do not evaluate the `.queryset` attribute directly, '
                'as the result will be cached and reused between requests. '
                'Use `.all()` or call `.get_queryset()` instead.'
            )
        cls.queryset._fetch_all = force_evaluation
 
    view = super(APIView, cls).as_view(**initkwargs)
    view.cls = cls
    view.initkwargs = initkwargs

4, into the parent class View class APIView class, what did look as_view method, the actual implementation as_view method of the View class is the implementation of dispatch APIView class method

@classonlymethod
 def as_view(cls, **initkwargs):
     """
     Main entry point for a request-response process.
     """
     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. as_view "
                             "only accepts arguments that are already "
                             "attributes of the class." % (cls.__name__, key))
 
     def view(request, *args, **kwargs):
         self = cls(**initkwargs)
         if hasattr(self, 'get') and not hasattr(self, 'head'):
             self.head = self.get
         self.request = request
         self.args = args
         self.kwargs = kwargs
         return self.dispatch(request, *args, **kwargs)
     view.view_class = cls
     view.view_initkwargs = initkwargs
 
     # take name and docstring from class
     update_wrapper(view, cls, updated=())
 
     # and possible attributes set by decorators
     # like csrf_exempt from dispatch
     update_wrapper(view, cls.dispatch, assigned=())
     return view

5, into the dispatch method APIView like, in fact, we need to focus on here is the initialmethod

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

6, into the initial approach here into our purview componentcheck_permissions

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)

7, enter check_permissions method, where the focus needs to lookself.get_permissions

What this method did, knowing what this approach, we look down at the back of this method

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)
            )

8, into the self.get_permissionsmethod, this is not very familiar with, and we've talked about authentication component is not very similar?

We need to define a class of our own in the view of the configuration of permission_classesthe list, and this list is that instance of the object class of each control authority

def get_permissions(self):
    """
    Instantiates and returns the list of permissions that this view requires.
    """
    return [permission() for permission in self.permission_classes]

9, following the return to Step 7, look down, you know how we configure this permission class

img

10. Here we define our own class privileges in accordance with the above analysis

What specific permission allows logic is our own set

class SVIPpermission(object):
    message = "只有超级用户才能访问"
    def has_permission(self,request,view):
        user_name = request.user
        user_type = models.User.objects.filter(name=user_name).first().user_type
        if user_type == 1:
            return True
        else:
            return False

Usage rights class in the view class

img

Second, the global configuration rights component

1. Determine the name of the default access control class

img

2, our access control class in a separate file

img

3, into the configuration settings

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES":(
        "app1.utils.Book_auther",
    ),
    "DEFAULT_PERMISSION_CLASSES_CLASSES": (
        "app1.utils.SVIPpermission",
    )
}

img

Guess you like

Origin www.cnblogs.com/fxyadela/p/11941771.html