[
课程介绍](_index_)
[
引入DjangoRESTframework](c01-introducetodrf_index)-[Web应用模式](c01-introducetodrf_separatedfrontendandbackend)
[
认识RESTful](c01-introducetodrf_introducetorest)
[
RESTful设计方法](c01-introducetodrf_howtodesignrest)
[
使用Django开发REST接口](c01-introducetodrf_developrestapiwithdjango)
[
明确REST接口开发的核心任务](c01-introducetodrf_coretasktodeveloprestapi)
[
DjangoRESTframework简介](c01-introducetodrf_aboutdrf)
[
DRF工程搭建](c02-drfproject_index)-[环境安装与配置](c02-drfproject_installandconfig)
[
见识DRF的魅力](c02-drfproject_thefirstdrfprogram)
[
Serializer序列化器](c03-serializer_index)-[定义Serializer](c03-serializer_declaring)
[
序列化使用](c03-serializer_serializing)
[
反序列化使用](c03-serializer_deserializing)
[
模型类序列化器ModelSerializer](c03-serializer_modelserializer)
[
视图](c04-view_index)-[Request与Response](c04-view_requestandresponse)
[
视图概览](c04-view_view)
[
视图说明](c04-view_viewintroduction)
[
视图集ViewSet](c04-view_viewset)
[
路由Router](c04-view_routers)
[
其他功能](c05-components_index)-[认证](c05-components_authentication)
[
权限](c05-components_permissions)
[
限流](c05-components_throttling)
[
过滤](c05-components_filtering)
[
排序](c05-components_ordering)
[
分页](c05-components_pagination)
[
版本](c05-components_versioning)
[
异常处理](c05-components_exceptions)
[
自动生成接口文档](c05-components_documents)
[Published with GitBook](https://www.gitbook.com)
课程介绍
权限Permissions
权限控制可以限制用户对于视图的访问和对于具体数据对象的访问。
- 在执行视图的dispatch()方法前,会先进行视图访问权限的判断
- 在通过get_object()获取具体对象时,会进行对象访问权限的判断
使用
可以在配置文件中设置默认的权限管理类,如 ``` REST_FRAMEWORK = { ‘DEFAULT_PERMISSION_CLASSES’: (
) }'rest_framework.permissions.IsAuthenticated',
如果未指明,则采用如下默认配置
‘DEFAULT_PERMISSION_CLASSES’: ( ‘rest_framework.permissions.AllowAny’, )
也可以在具体的视图中通过permission_classes属性来设置,如
from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView
class ExampleView(APIView): permission_classes = (IsAuthenticated,) …
### 提供的权限- AllowAny 允许所有用户- IsAuthenticated 仅通过认证的用户- IsAdminUser 仅管理员用户- IsAuthenticatedOrReadOnly 认证的用户可以完全操作,否则只能get读取### 举例
from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.generics import RetrieveAPIView
class BookDetailView(RetrieveAPIView): queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer authentication_classes = [SessionAuthentication] permission_classes = [IsAuthenticated]
### 自定义权限如需自定义权限,需继承rest_framework.permissions.BasePermission父类,并实现以下两个任何一个方法或全部- `.has_permission(self, request, view)`<br /> 是否可以访问视图, view表示当前视图对象- `.has_object_permission(self, request, view, obj)`<br /> 是否可以访问数据对象, view表示当前视图, obj为数据对象例如:
class MyPermission(BasePermission): def has_object_permission(self, request, view, obj): “””控制对obj对象的访问权限,此案例决绝所有对对象的访问””” return False
class BookInfoViewSet(ModelViewSet): queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer permission_classes = [IsAuthenticated, MyPermission]
