赞
踩
IsAuthenticated权限类将拒绝任何未经身份验证的用户的权限,否则将允许权限。
在向需要加入的viewset中加入如下代码即可实现权限认证功能
permission_classes = (IsAuthenticated,)
因为IsAuthenticated权限类功能较为单调只能简单的判断用户是否为注册用户而无法进行更细致的判断,如判断数据库中的此条收藏记录的用户是否为登录用户,这就需要自定义权限认证文件了。代码如下
# -*- coding: utf-8 -*- from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Instance must have an attribute named `owner`. #用来判断当前用户对象是否和登录用户相同 return obj.user == request.user
重载重载get_queryset()方法,实现只获取当前用户的收藏记录
class UserFavViewset(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin,
mixins.DestroyModelMixin, viewsets.GenericViewSet):
queryset = UserFav.objects.all()
serializer_class = UserFavSerializer
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)#验证必须要登录
def get_queryset(self):
return UserFav.objects.filter(user=self.request.user)
只需要增加url就可以访问
url(r'docs/', include_docs_urls(title="学习设计")),
在写代码的过程中加上规定形式的注释与help_text=“字段描述”,drf就能根据注释自动生成文档
某某viewset
"""
create:
功能描述
destroy:
功能描述
list:
功能描述
retrieve:
功能描述
"""
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。