Django REST Framework视图集按操作权限 [英] Django REST Framework viewset per-action permissions

查看:113
本文介绍了Django REST Framework视图集按操作权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有最佳实践为给定的 APIView ViewSet 的每个操作分配不同的权限?

Is there a best practice to assign a different permission to each action of a given APIView or ViewSet?

假设我定义了一些权限类,例如 IsAdmin, IsRole1, IsRole2等,并且我想为单个操作授予不同的权限(例如,一个用户使用Role1可以创建或检索,使用Role2的用户可以更新,并且只有管理员可以删除。)

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 ,您可以在其中访问请求 view 对象。您可以检查 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.

看看提供的 IsAuthenticatedOrReadOnly 类(以及其他类)是一个简单易用的好例子。

Have a look at the provided IsAuthenticatedOrReadOnly class (and others) for a good example of how easy it is.

我希望能帮上忙。

这篇关于Django REST Framework视图集按操作权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆