问题描述
我是Django + Django Rest-framework开发的新手,我正在开发一个提供REST Api访问的项目。我想知道为给定的ApiView或Viewset的每个动作分配不同的权限是最好的做法。
I'm a newbie in developing with Django + Django Rest-framework and I'm working on a project that provides REST Api access. I was wondering what is the best practice to assign a different permission to each action of a given ApiView or Viewset.
我们假设我定义了一些权限类,如IsAdmin ,'IsRole1','IsRole2',...,我想授予不同的权限,单一动作(例如,一个用户角色1可以创建或检索,一个用户可以更新,只有一个管理员可以删除)。
Let's suppose I defined some permissions classes such as 'IsAdmin', 'IsRole1', 'IsRole2', ..., and I want to grant different permissions to the single actions (e.g. a user with Role1 can create or retrieve, a user with Role2 can update, and only an Admin can delete).
如何构建基于类的视图,以便将权限类分配给创建,列表,检索,更新,删除 行动?
我试图这样做有一个类可以重用于具有相同权限模式的不同表。
How can I structure a class based view in order to assign a permission class to the 'create', 'list', 'retrieve', 'update', 'delete' actions?I'm trying to do so to have a class that can be reused for different tables that have the same permission pattern.
也许我只是溺水在一英寸的水中,谢谢你的回复。
Maybe I'm just drowning in an inch of water, thank you for your replies.
推荐答案
您可以创建一个,扩展DRF的 BasePermission
。
You can create a custom permission class extending DRF's BasePermission
.
您实现 has_permission
您可以访问请求
和视图
对象。您可以检查 request.user
以获取适当的角色并返回 True
/ False
酌情。
You implement has_permission
where you have access to the request
and view
objects. You can check request.user
for the appropriate role and return True
/False
as appropriate.
查看提供的类(和其他人)一个很好的例子,它是多么容易。
Have a look at the provided IsAuthenticatedOrReadOnly class (and others) for a good example of how easy it is.
我希望有帮助。
这篇关于Django rest-framework每个操作权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!