Django restframework user authority authentication component addition and source code analysis

Source code analysis of user authorization verification is similar to user login verification, but in order to increase memory, it is necessary to add again,

Note: be sure to follow the blogger's comments to see the Chinese comments of the code and the following line of code!!!

1. Prepare a routing and view class. The global routing configuration is ignored temporarily. When the process is executed to the as under the view class of the following url: groupsSelectAll - > groupsview_ View () method

from django.conf.urls import url

from . import views

app_name = '[words]'
urlpatterns = [
    url(r'groupsSelectAll/', views.GroupsView.as_view(), name="groupsSelectAll"),   # Phrase information query all

class GroupsView(APIView):

    def get(self, request):
        conditions = {
            "id": request.query_params.get("wid"),
            "name": request.query_params.get("name"),
            "start_time": request.query_params.get("start_time"),
            "end_time": request.query_params.get("end_time"),
        res = DataManager.select_by_conditions("words_groups", None, **conditions)
        return Response(data={"code": 200, "result": res})

2. But there is no as under the GroupsView class_ View method, then go to its parent class APIView to view (click in to see as_view method), here the blogger only copies the method source code, and you only need to see the Chinese comments and the code statements below. In this method, it is worth mentioning the super keyword. If the request view class (that is, GroupsView class, if it inherits multiple parent classes) has another parent class, it will first check whether the parent class has as_view method. In this case, it will execute as in the parent class view of APIView_ View method, and then let's look at the as of the parent class view again_ View method. First as_ The view method is of the APIView class, the second as_ The view method is of the view class.


3. We are in the second as_ In the view method, you can know that self is the object of our request view class. Through this self, you call the dispatch method. There is no dispatch method in the request view class. Do you want to execute the dispatch method in the APIView class again.


4. We don't need to look at other codes. We can directly look at the initial method, because this initial method has the function of permission verification.


5. This is the trick of our user authority verification. Blogger adds some code of APIView, i.e. check_ The code used by the permission method. We can view the self.check_permissions(request), click in to check_permission () method, you can see get_permissions method. This method has self.permission_classes variable, that is self.permission_classes = api_ settings.DEFAULT_ PERMISSION_ Class, and then it is very similar to user login authentication in the previous article. If there is no such variable name and value (the value is a list) in the request view class, the rest in the global configuration file will be used_ FRAMEWORK={"DEFAULT_ PERMISSION_ Classes ": [" full path of permission verification class "]}, or we can add this variable and value to the request view class

class APIView(View):

    # If this variable and value are not available in the request view class, the global profile value is used
    permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES

    def check_permissions(self, request):
        Check if the request should be permitted.
        Raises an appropriate exception if the request is not permitted.
        # Object of circular permission class
        for permission in self.get_permissions():
            # Under execution object has_permission()Method, verify if you have permission (the default is permission)
            if not permission.has_permission(request, self):
                    request, message=getattr(permission, 'message', None)

    def get_permissions(self):
        Instantiates and returns the list of permissions that this view requires.
        # The object returned is a permission class object
        return [permission() for permission in self.permission_classes]

    def permission_denied(self, request, message=None):
        If request is not permitted, determine what kind of exception to raise.
        # If the user has permission class but does not log in, an exception is thrown that the user does not log in
        if request.authenticators and not request.successful_authenticator:
            raise exceptions.NotAuthenticated()
        # Throw an exception without permission
        raise exceptions.PermissionDenied(detail=message)

6. In the above APIView class, if not permission.has_permission(request, self), we can directly click in to check has_permission method. Generally, if we customize the user permission verification class, we need to inherit the BasePermission class, so we can directly override the has_permission method, which needs to verify whether the currently logged in user has the permission of a certain module. In this way, we can customize a class with only the access rights of recharge called VIP or SVIP users (this is just my idea)

Tags: Python Django REST

Posted on Mon, 01 Jun 2020 05:53:49 -0400 by if