04_Tutorial 4: Authentication & Permissions 认证和权限
1、认证和权限
0、文档
https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/
1、外键:models
model中,关联django自带的 auth.User
owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
# 设置related_name参数来覆盖原名称owner_id(ORM查询时),实质,DB中还是owner_id
highlighted = models.TextField()
class Meta:
ordering = ['created']
# def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
def save(self, *args, **kwargs):
"""
使用pygments库,创建一个高亮显示的HTML,表示代码段
"""
lexer = get_lexer_by_name(self.language)
linenos = self.linenos and 'table' or False
options = self.title and {'title': self.title} or {}
formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super(Snippet, self).save(*args, **kwargs) # 继承父类Model的save
2、外键,序列化 GET方法:source
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all()) # 添加一个显式字段 外键
class Meta:
model = User
fields = ['id', 'username', 'snippets']
class SnippetSerializer(serializers.ModelSerializer):
# # Tutorial 4: Authentication & Permissions
# owner = serializers.ReadOnlyField(source='owner.username') # source参数控制哪个属性用于填充字段
owner = serializers.CharField(read_only=True, source='owner.username') # 外键source,序列化的时候,GET方法
class Meta:
model = Snippet
fields = ['id', 'title', 'code', 'linenos', 'language', 'style', 'owner']
3、外键:视图,POST方法:perform_create()
class SnippetList(generics.ListCreateAPIView): # list create
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
# IsAuthenticatedOrReadOnly 只有经过身份验证的用户才能创建,更新和删除代码片段
# IsOwnerOrReadOnly 创建代码片段的用户才能更新或删除它
def perform_create(self, serializer): # 关联user, save的同时也保存owner, 外键 POST方法!!!!
serializer.save(owner=self.request.user) # perform_create() 实质调用的是 serializer.save()
4、权限组件:认证用户才可以增删改查
from rest_framework import permissions # 权限认证组件
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): # 检索,更新,删除
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
5、自定义权限:谁创建的谁才可以操作
1、自定义
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
自定义权限,只允许,对象的所有者编辑它
"""
def has_object_permission(self, request, view, obj):
# 读取权限,允许任何请求
# 所以我们总是允许GET,HEAD或OPTIONS请求。
if request.method in permissions.SAFE_METHODS: # 请求方法ok
return True
# 只有该snippet的所有者才允许写权限。
return obj.owner == request.user # user=owner
2、使用
from snippets.permissions import IsOwnerOrReadOnly
class SnippetList(generics.ListCreateAPIView): # list create
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
6、效果