Creating a customized permission class for object-level permissions

Create a new Python file named customized_permissions.py within the games_service/games folder and enter the following code that declares the new IsOwnerOrReadOnly class. The code file for the sample is included in the restful_python_2_07_04 folder, in the Django01/games-service/games/customized_permissions.py file:

from rest_framework import permissions 
 
 
class IsOwnerOrReadOnly(permissions.BasePermission): 
    def has_object_permission(self, request, view, obj): 
        if request.method in permissions.SAFE_METHODS: 
            return True 
        else: 
            return obj.owner == request.user 

The rest_framework.permissions.BasePermission class is the base class from which all permission classes should inherit. The previous lines declare the IsOwnerOrReadOnly class as a subclass of the BasePermission superclass and override the has_object_permission method, defined in the superclass, that returns a bool value indicating whether the permission should be granted or not.

If the HTTP verb specified in the request, available in the request.method attribute is any of the three safe methods specified in permission.SAFE_METHODS (GET, HEAD, or OPTIONS), the has_object_permission method returns True and grants permission to the request. These HTTP verbs do not make changes to the related resources, and therefore, they are included in the permissions.SAFE_METHODS tuple of string.

If the HTTP verb specified in the request, available in the request.method attribute, is not any of the three safe methods, the code returns True and grants permission only when the owner attribute of the received obj, available in the obj.owner attribute, matches the user that originated the request (request.user). This way, only the owner of the related resource will be granted permission to requests that include HTTP verbs that aren't safe.

We will use the new IsOwnerOrReadOnly permission class to make sure that only the game owners can make changes to an existing game. We will combine this permission class with the rest_framework.permissions.IsAuthenticatedOrReadOnly permission class that only allows read-only access to resources when the request is not authenticated as a user.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.40.53