definitial(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)
defget_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ return [permission() for permission in self.permission_classes]
from rest_framework.permissions import BasePermission from django.contrib.auth.models import Group
classMyPermission(BasePermission): defhas_permission(self, request, view): # 只读接口判断 r1 = request.method in ('GET', 'HEAD', 'OPTIONS') # group为有权限的分组 group = Group.objects.filter(name='管理员').first() # groups为当前用户所属的所有分组 groups = request.user.groups.all() r2 = group and groups # group和groups必须有值 r3 = group in groups # 读接口大家都有权限,写接口必须为指定分组下的登陆用户 return r1 or (r2 and r3)
views.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14
from rest_framework.views import APIView
from utils.permissions import MyPermission from utils.response import APIResponse