permission_classes = IsAuthenticated ReadOnly full example
Here is a full example of using permission_classes with IsAuthenticated or ReadOnly for a view in Django REST framework:
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated, BasePermission
from rest_framework.response import Response
class ReadOnly(BasePermission):
def has_permission(self, request, view):
return request.method in ['GET', 'HEAD', 'OPTIONS']
class MyView(APIView):
permission_classes = [IsAuthenticated | ReadOnly]
def get(self, request, format=None):
content = {'message': 'Hello, world!'}
return Response(content)
In this example, we define a custom permission class ReadOnly which allows only read-only requests (GET, HEAD, OPTIONS). We then define a view MyView which requires either authentication (IsAuthenticated) or read-only access (ReadOnly) to access.
For authenticated requests, the request.user will be set to the authenticated user, and for read-only requests, the request.user will be AnonymousUser.
When the GET method is called, the view returns a simple JSON response with a message.
Note that IsAuthenticated | ReadOnly is a shorthand way of using a logical OR operator between the two permission classes. The | operator can also be replaced with the + operator to use a logical AND operator between the permission classes.
原文地址: http://www.cveoy.top/t/topic/5Uf 著作权归作者所有。请勿转载和采集!