我想在我的视图上应用IsAdminUser权限。我可以通过设置permission_classes属性来做到这一点:
class UserProfileView(APIView):
permission_classes = [IsAdminUser,]
def get(self, request, pk=None):
...但是,如果我尝试使用装饰器进行同样的操作,那么它似乎是无效的,并且只对经过身份验证的用户进行检查。
class UserProfileView(APIView):
@permission_classes([IsAdminUser])
def get(self, request, pk=None):
...我想知道它为什么会这样做。我做错什么了吗?我的环境配置: Python==3.7.6,Django==2.2.10,djangorestframework==3.11.0,django-oauth-toolkit=1.2.0
发布于 2020-03-27 06:16:44
它不适用于APIView处理程序,@permission_classes只设置func.permission_classes = permission_classes,然后@api_view装饰器使用APIView-based类包装函数。当APIView调用一个处理程序时,它不会检查该处理程序上的permission_classes集,因为这些检查是在initial方法中进行的。这里是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)如果要对不同的处理程序(如get或post)应用不同的权限,可以:
permission_classes
check_permissions 中。
https://stackoverflow.com/questions/60874819
复制相似问题