我对Django-rest-framework中的BasePermission感到困惑。
这里我定义了一个类:IsAuthenticatedAndOwner。
class IsAuthenticatedAndOwner(BasePermission):
message = 'You must be the owner of this object.'
def has_permission(self, request, view):
print('called')
return False
def has_object_permission(self, request, view, obj):
# return obj.user == request.user
return False在views.py中使用
class StudentUpdateAPIView(RetrieveUpdateAPIView):
serializer_class = StudentCreateUpdateSerializer
queryset = Student.objects.all()
lookup_field = 'pk'
permissions_classes = [IsAuthenticatedAndOwner]但它根本不起作用。每个人都可以传递权限并更新数据。
未打印called。
我曾经定义过这个类:IsNotAuthenticated
class IsNotAuthenticated(BasePermission):
message = 'You are already logged in.'
def has_permission(self, request, view):
return not request.user.is_authenticated()它在函数中运行良好
class UserCreateAPIView(CreateAPIView):
serializer_class = UserCreateSerializer
queryset = User.objects.all()
permission_classes = [IsNotAuthenticated]那么,上面的例子和has_object_permission & has_permission函数有什么不同呢
发布于 2017-03-28 21:23:49
基本上,第一个代码拒绝所有内容,因为has_permission返回False。
has_permission是在调用has_object_permission之前进行的检查。这意味着在你有机会检查所有权测试之前,你需要得到has_permission的允许。
你想要的是:
class IsAuthenticatedAndOwner(BasePermission):
message = 'You must be the owner of this object.'
def has_permission(self, request, view):
return request.user and request.user.is_authenticated
def has_object_permission(self, request, view, obj):
return obj.user == request.user这也将允许经过身份验证的用户创建新项目或列出它们。
发布于 2018-04-03 17:07:56
我们在BasePermission类上有以下两个权限方法:
def has_permission(self, request, view)def has_object_permission(self, request, view, obj)这两种不同的方法被称为,用于限制未经授权的用户对数据插入和操作的。
所有的HTTP请求都会调用has_permission,而has_object_permission则是从DRF的方法def get_object(self)中调用的。因此,has_object_permission方法适用于GET、PUT、DELETE,而不适用于POST请求。
摘要:
permission_classes在定义的list.has_object_permission方法上循环,在POST方法中除外的True方法返回值之后调用POST方法(在has_permission方法中,只有False为executed).permission_classes方法返回all值,请求不会获得任何权限,也不会再循环,否则,它检查looping.has_permission方法上的所有权限将在False上调用(GET,POST,PUT,DELETE) HTTP request.has_object_permission方法将不会在has_permission请求上调用,因此我们需要将其限制在has_permission方法中。发布于 2021-02-03 00:10:34
我认为这会有所帮助:
class IsAuthorOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
# Read-only permissions are allowed for any request
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the author of a post
return obj.user == request.userhttps://stackoverflow.com/questions/43064417
复制相似问题