每个视图的Django Rest Framework自定义权限 [英] Django Rest Framework custom permissions per view
问题描述
我想基于视图+方法+用户权限在Django Rest Framework中创建权限.
I want to create permissions in Django Rest Framework, based on view + method + user permissions.
是否有一种无需手动写入每个权限并检查用户所在的组的权限即可实现此目标的方法?
Is there a way to achieve this without manually writing each permission, and checking the permissions of the group that the user is in?
另外,我面临的另一个问题是,权限对象被绑定到某个模型上.由于我有影响不同模型的视图,或者我想对方法PUT授予不同的权限,具体取决于我访问的视图(因为它影响不同的字段),因此我希望我的权限绑定到某个视图,而不是某种模型.
Also, another problem i am facing with, is that permission objects are tied up to a certain model. Since i have views that affect different models, or i want to grant different permissions on the method PUT, depending on what view i accessed (because it affects different fields), i want my permissions to be tied to a certain view, and not to a certain model.
有人知道该怎么做吗?
我正在寻找一种解决方案:
I am looking for a solution in the sort of:
1)使用以下参数创建一个Permissions对象:View_affected,list_of_allowed_methods(GET,POST等)
1) Create a Permissions object with the following parameters: View_affected, list_of_allowed_methods(GET,POST,etc.)
2)创建具有该权限的组对象
2) Create a Group object that has that permission associated
3)将用户添加到组
4)让我的默认权限类别处理所有事情.
4) Have my default permission class take care of everything.
从我现在所拥有的来看,给我带来麻烦的步骤是步骤1.因为我看不到将View与Permission绑定的方法,并且因为Permissions需要一个模型,所以我不想要一个模型.
From what i have now, the step that is giving me problems is step1. Because i see no way of tying a Permission with a View, and because Permissions ask for a model, and i do not want a model.
任何帮助将不胜感激!
推荐答案
嗯,使用DRF可以轻松完成第一步.参见 http://www.django-rest-framework.org/api-guide/permissions#custom-permissions .
Well, the first step could be done easy with DRF. See http://www.django-rest-framework.org/api-guide/permissions#custom-permissions.
您必须执行以下操作:
from functools import partial
from rest_framework import permissions
class MyPermission(permissions.BasePermission):
def __init__(self, allowed_methods):
super().__init__()
self.allowed_methods = allowed_methods
def has_permission(self, request, view):
return request.method in self.allowed_methods
class ExampleView(APIView):
permission_classes = (partial(MyPermission, ['GET', 'HEAD']),)
这篇关于每个视图的Django Rest Framework自定义权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!