django rest framework api授权
djangorestf 官方文档 授权与认证教程
permissions.py
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
'''
常规的授权是 只有拥有者才能编辑它
'''
def has_object_permission(self, request, view, obj):
# 读权限 向所有请求开放
# 所以我们总是允许get, head or options requests.
if request.method in permissions.SAFE_METHODS:
return True
# 写权限 只给拥有者
return obj.owner == request.user
view.py
'''基于泛型类的视图'''
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer, UserSerializer
from rest_framework import generics
from snippets.permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User
class UserList(generics.ListAPIView):
'''
User表的列表api视图 查 增 操作
'''
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveDestroyAPIView):
'''
User表的详情api视图 查 改 删操作
'''
queryset = User.objects.all()
serializer_class = UserSerializer
class SnippetList(generics.ListCreateAPIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class SnippetDetail(generics.RetrieveDestroyAPIView):
# detail 所有人都能读,但是只有拥有者可以更改
# permissions.IsAuthenticatedOrReadOnly 表示没有认证的人有读的权限,认证的人有所有权限
# IsOwnerOrReadOnly 通过了前面的授权之后,还要通过这个授权
# 当所有的授权都通过的时候 所有的对象实例都返回true 表示授权通过
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer