Django REST框架 - 每个方法分开的权限 [英] Django REST Framework - Separate permissions per methods

查看:216
本文介绍了Django REST框架 - 每个方法分开的权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django REST框架编写API,我想知道在使用基于类的视图时是否可以指定每个方法的权限。



阅读文档我看到这是很容易做的,如果你是编写基于函数的视图,只需使用 @permission_classes 装饰器,您可以通过权限保护视图的功能。但是,当使用CBVs与API $ <$ code>类时,我看不到同样的方法,因为我指定了具有$ $ c $的完整类的权限c> permission_classes 属性,但这将被应用于所有类方法( get post put ...)。



那么可以使用CBV编写的API视图并且还为视图类的每个方法指定不同的权限?

解决方案

权限应用于整个View类,但是在您的授权决定中考虑请求的方面(如GET或POST等方法)。



请参阅内置的 IsAuthenticatedOrReadOnly 作为示例:

  SAFE_METHODS = ['GET','HEAD','OPTIONS'] 

class IsAuthenticatedOrReadOnly(BasePermission):

该请求作为用户进行身份验证,或是一个读取y请求


def has_permission(self,request,view):
if(request.method in SAFE_METHODS or
request.user and
request.user.is_authenticated()):
返回True
返回False


I am writing an API using Django REST Framework and I am wondering if can specify permissions per method when using class based views.

Reading the documentation I see that is quite easy to do if you are writing function based views, just using the @permission_classes decorator over the function of the views you want to protect with permissions. However, I don't see a way to do the same when using CBVs with the APIView class, because then I specify the permissions for the full class with the permission_classes attribute, but that will be applied then to all class methods (get, post, put...).

So, is it possible to have the API views written with CBVs and also specify different permissions for each method of a view class?

解决方案

Permissions are applied to the entire View class, but you can take into account aspects of the request (like the method such as GET or POST) in your authorization decision.

See the built-in IsAuthenticatedOrReadOnly as an example:

SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']

class IsAuthenticatedOrReadOnly(BasePermission):
    """
    The request is authenticated as a user, or is a read-only request.
    """

    def has_permission(self, request, view):
        if (request.method in SAFE_METHODS or
            request.user and
            request.user.is_authenticated()):
            return True
        return False

这篇关于Django REST框架 - 每个方法分开的权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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