[英]Django DRF @permission_classes not working for IsAdminUser permission
I want to apply IsAdminUser permission on my view.我想对我的视图应用IsAdminUser权限。 I am able to do it by setting the permission_classes attribute:
我可以通过设置 permission_classes 属性来做到这一点:
class UserProfileView(APIView):
permission_classes = [IsAdminUser,]
def get(self, request, pk=None):
...
However, if I try to do the same using decorator then it seems to be ineffective and checks only for authenticated users.但是,如果我尝试使用装饰器来做同样的事情,那么它似乎是无效的并且只检查经过身份验证的用户。
class UserProfileView(APIView):
@permission_classes([IsAdminUser])
def get(self, request, pk=None):
...
I want to understand why is it behaving so.我想了解它为什么会这样。 Am I doing anything wrong?
我做错了什么吗? My environment configuration: Python==3.7.6, Django==2.2.10, djangorestframework==3.11.0, django-oauth-toolkit==1.2.0
我的环境配置:Python==3.7.6、Django==2.2.10、djangorestframework==3.11.0、django-oauth-toolkit==1.2.0
It is not supposed to work on APIView
handlers, @permission_classes
just sets func.permission_classes = permission_classes
and then @api_view
decorator wraps function with APIView
-based class.它不应该在
APIView
处理程序上工作, APIView
@permission_classes
只是设置func.permission_classes = permission_classes
然后@api_view
装饰器使用基于APIView
的类包装函数。 When APIView
calls a handler it does not check permission_classes
set on that handler, as these checks are made in the initial
method.当
APIView
调用处理程序时,它不会检查在该处理程序上设置的permission_classes
,因为这些检查是在initial
方法中进行的。 Here is a part of APIView.dispatch
:这是
APIView.dispatch
的一部分:
self.initial(request, *args, **kwargs)
# part of initial:
# self.check_permissions(request)
# 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)
If you want to apply different permissions to different handlers (like get or post) you can either:如果您想对不同的处理程序(如 get 或 post)应用不同的权限,您可以:
permission_classes
permission_classes
指定check_permissions
check_permissions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.