博客五部曲之三 - 博客RESTful


1266 浏览 5 years, 2 months

11 定制权限

版权声明: 转载请注明出处 http://www.codingsoho.com/

权限模块

这一节我们将会讨论用户权限,用户可以在当前app里做哪些事情,这个不是授权authentication,这个是权限permission。

这时我们会用到 restful的模块permission

权限模块

导入权限模块

from rest_framework.permissions import(
    AllowAny,
    IsAuthenticated,
    IsAdminUser,
    IsAuthenticatedOrReadonly,
    )

接着在视图里添加权限控制,如果我们只运行授权用户创建post,可以添加如下

class PostCreateAPIView(CreateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostCreateUpdateSerializer
    permission_classes = [IsAuthenticated]

这个时候,如果我们未授权即创建,http://127.0.0.1:8000/api/posts/create, 会有如下报错

自定义权限类

我们也可以自定义自己的权限类,比如我们希望只有作者可以访问自己的post,我们可以添加下面的自定义类

创建新的文件

permissions.py

权限可以针对某一具体对象或者通用权限

from rest_framework.permissions import BasePermission, SAFE_METHODS
class IsOwnerReadonly(BasePermission):
    message = "you must be the owener of this object"
    my_safe_method = ["PUT","GET"]
    def has_permission(self, request, view):
        if request.method in self.my_safe_method:
            return True
        return False
    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True
        return obj.user == request.user

在上面的两个函数中,has_object_permission仅针对当前对象,如果和登陆用户是同一用户,那么允许访问。

SAFE_METHOD为(u'GET', u'HEAD', u'OPTIONS')