django-rest-framework:在ViewSet更新方法中添加其他权限 [英] django-rest-framework: add additional permission in ViewSet update method
问题描述
我有以下代码:
I have the following code:
class UsersViewSet(viewsets.ModelViewSet):
model = Users
permission_classes = (IsAuthenticated,)
def update(self, request, *args, **kwargs):
return super(UsersViewSet, self).update(request, *args, **kwargs)
问题是:
- 如何才能为update方法添加额外的权限? (需要获取isAuthenticated +权限)
- 仅覆盖更新方法的权限? (需要获取只有权限没有被授权)
视图中的其他方法应该具有IsAuthenticated权限
我可以使用装饰器?或其他什么?
Can I make it with decorator?Or anything else?
想要得到这样的东西:
Wanna get something like that:
@permission_classes((IsAuthenticated, AdditionalPermission ))
def update:
pass
但是如果我写这个代码,则不通过请求检查第二个权限
But if i write this code the second permission is not checked through request
推荐答案
docs,你应该发送一个列表到装饰器(而不是一个元组)。所以应该是这样的:
There is a small mistake in the docs, you should be sending a list to the decorator (not a tuple). So it should be like this:
@permission_classes([IsAuthenticated, AdditionalPermission, ])
def update:
pass
回答您的问题:
如何为更新方法添加额外的权限?
首先,您应该知道DRF首先检查全局权限那些来自设置文件),然后查看权限(在 permission_classes 中声明 - 如果这些存在,它们将覆盖全局权限),并且只有在方法权限之后(用decorator声明为@ permission_classes )。所以做另外一种方法是这样的:
First of all, you should know that DRF first checks for global permissions (those from the settings file), then for view permissions (declared in permission_classes -- if these exist, they will override global permissions) and only after that for method permissions (declared with the decorator @permission_classes). So another way to do the above is like this:
@permission_classes([AdditionalPermission, ])
def update:
pass
由于 ISAuthenticated 已在整个视图中设置在任何其他权限之前,它将始终被检查。
Since ISAuthenticated is already set on the entire view, it will always be checked BEFORE any other permission.
仅对更新方法覆盖权限?
嗯,这很难(呃),但不是不可能的。您可以:
Well, this is hard(er), but not impossible. You can:
- 设置每种方法的权限,并将其从类中删除
- 修改您的AdditionalPermission类,以便如果方法不是更新,它也会检查用户身份验证。
- set the permissions for each method and remove it from the class
- modify your AdditionalPermission class so that it also checks for user authentication if the method is not update.
祝你好运。
更新
似乎DRF装饰器似乎没有真正工作至少不适合我),这是我可以想出的最好的解决方案:
As it seems that DRF decorators don't really work (at least not for me), this is the best solution I could come up with:
def get_permissions(self):
# Your logic should be all here
if self.request.method == 'GET':
self.permission_classes = [DummyPermission, ]
else:
self.permission_classes = [IsAuthenticated, ]
return super(UsersViewSet, self).get_permissions()
这实际上适用于您所要求的两种情况,但需要更多工作。不过,我已经测试过了,而且这样做了。
This actually works for both cases that you asked, but requires a bit more work. However, I've tested it and it does the job.
这篇关于django-rest-framework:在ViewSet更新方法中添加其他权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!