每个方法的单独权限

每个方法的单独权限

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

问题描述

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

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

阅读文档我发现如果您正在编写基于函数的视图,这很容易做到,只需在要使用权限保护的视图的函数上使用 @permission_classes 装饰器即可.但是,在将 CBV 与 APIView 类一起使用时,我没有看到执行相同操作的方法,因为随后我使用 permission_classes 属性指定了完整类的权限,但这将应用于所有类方法(getpostput...).

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...).

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

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

推荐答案

权限适用于整个 View 类,但您可以在授权决策中考虑请求的各个方面(例如 GET 或 POST 等方法).

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.

以内置的IsAuthenticatedOrReadOnly为例:

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 Framework - 每个方法的单独权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 08:31