classAllowAny(BasePermission): """ Allow any access. This isn't strictly required, since you could use an empty permission_classes list, but it's useful because it makes the intention more explicit. """ # 游客与登录用户都拥有所有权限 defhas_permission(self, request, view): returnTrue
classIsAuthenticated(BasePermission): """ Allows access only to authenticated users. """
defhas_permission(self, request, view): # 只有合法用户有权限,游客无任何权限: # 有值且认证通过 returnbool(request.user and request.user.is_authenticated)
classIsAuthenticatedOrReadOnly(BasePermission): defhas_permission(self, request, view): returnbool( # 如果是读请求,不校验用户,直接返回 request.method in SAFE_METHODS or # 登录用户有所有权限,游客只读 request.user classAllowAny(BasePermission): """ Allow any access. This isn't strictly required, since you could use an empty permission_classes list, but it's useful because it makes the intention more explicit. """ # 游客与登录用户都拥有所有权限 defhas_permission(self, request, view): returnTrue
classIsAuthenticated(BasePermission): """ Allows access only to authenticated users. """
defhas_permission(self, request, view): # 只有合法用户有权限,游客无任何权限: # 有值且认证通过 returnbool(request.user and request.user.is_authenticated)
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly from rest_framework.views import APIView from rest_framework.generics import GenericAPIView from rest_framework.viewsets import GenericViewSet, ViewSet
from rest_framework.permissions import BasePermission, SAFE_METHODS from django.contrib.auth.models import Group
classMyPermission(BasePermission):
defhas_permission(self, request, view): # values_list(falt=True) 获取列表转为集合,与目标求交集 group = Group.objects.filter(name='administrator').first() groups = request.user.groups.all() returnbool( request.method in ('GET', 'HEAD', 'OPTIONS') or group and groups and group from rest_framework.permissions import BasePermission, SAFE_METHODS from django.contrib.auth.models import Group
classMyPermission(BasePermission):
defhas_permission(self, request, view): # values_list(falt=True) 获取列表转为集合,与目标求交集 group = Group.objects.filter(name='administrator').first() groups = request.user.groups.all() returnbool( request.method in ('GET', 'HEAD', 'OPTIONS') or group and groups and group in groups )
views.py
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly from rest_framework.views import APIView from rest_framework.generics import GenericAPIView from rest_framework.viewsets import GenericViewSet, ViewSet
from api.permissions import MyPermission from utils.response import APIResponse