DRF用户列表/详情权限控制

编程

def dispatch(self, request, *args, **kwargs):

try:

self.initial(request, *args, **kwargs)

# Get the appropriate handler method

if request.method.lower() in self.http_method_names:

handler = getattr(self, request.method.lower(),

self.http_method_not_allowed)

else:

handler = self.http_method_not_allowed

response = handler(request, *args, **kwargs)

except Exception as exc:

response = self.handle_exception(exc)

self.initial

    def initial(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)

def check_permissions(self, request):

"""

Check if the request should be permitted.

Raises an appropriate exception if the request is not permitted.

"""

for permission in self.get_permissions():

if not permission.has_permission(request, self):

self.permission_denied(

request, message=getattr(permission, "message", None)

)

def check_object_permissions(self, request, obj):

"""

Check if the request should be permitted for a given object.

Raises an appropriate exception if the request is not permitted.

"""

for permission in self.get_permissions():

if not permission.has_object_permission(request, self, obj):

self.permission_denied(

request, message=getattr(permission, "message", None)

)

对象级别的权限控制.

    def get_object(self):

"""

Returns the object the view is displaying.

You may want to override this if you need to provide non-standard

queryset lookups. Eg if objects are referenced using multiple

keyword arguments in the url conf.

"""

queryset = self.filter_queryset(self.get_queryset())

# Perform the lookup filtering.

lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

assert lookup_url_kwarg in self.kwargs, (

"Expected view %s to be called with a URL keyword argument "

"named "%s". Fix your URL conf, or set the `.lookup_field` "

"attribute on the view correctly." %

(self.__class__.__name__, lookup_url_kwarg)

)

filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}

obj = get_object_or_404(queryset, **filter_kwargs)

# May raise a permission denied

self.check_object_permissions(self.request, obj)

return obj

实现需求

  • 超级用户,查看用户列表,所有用户
  • 普通用户只能查看用户自己详情

apps.views.py

class UserViewSet(mixins.CreateModelMixin,

mixins.RetrieveModelMixin,

mixins.DestroyModelMixin,

mixins.ListModelMixin,

GenericViewSet):

permission_classes = [IsAdminUser]

authentication_classes = [

JSONWebTokenAuthentication, SessionAuthentication]

queryset = User.objects.all()

.filter(is_deleted=False).order_by("id")

serializer_map = {

"list": UserSerializer,

"retrieve": UserSerializer,

"create": UserCreateSerializer,

}

def get_serializer_class(self):

return self.serializer_map.get(self.action, UserSerializer)

def get_permissions(self):

if self.action in ["retrieve"]:

return [IsUserSelfPermission()]

return [permission() for permission in self.permission_classes]

  • list: 超级管理者, 后台查看用户列表
  • retrieve: 用户自己和超级管理者(超级管理者,查看用户详情)

以上是 DRF用户列表/详情权限控制 的全部内容, 来源链接: utcz.com/z/515246.html

回到顶部