1,认证Authentication
-
常见的认证方式
- BasicAuthentication: 用于测试, http认证
- SessionAuthentication: 验证用户是否是注册的用户
-
1,配置全局认证
REST_FRAMEWORK = { # 全局的配置 # 1, 认证 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.BasicAuthentication', # 基本认证 'rest_framework.authentication.SessionAuthentication', # session认证 ) }
-
2,配置局部认证
class BookInfoView(ModelViewSet): queryset = BookInfo.objects.all() serializer_class = BookInfoModelSerializer # 局部配置 # 1,认证 from rest_framework.authentication import SessionAuthentication authentication_classes = (SessionAuthentication, )
2,权限Permissions
-
配置代码:
-
1,全局配置(settings.py)
REST_FRAMEWORK = { ... # 2, 权限 'DEFAULT_PERMISSION_CLASSES': ( # 'rest_framework.permissions.IsAuthenticated', # 允许普通用户访问 # 'rest_framework.permissions.AllowAny', # 允许所有用户 'rest_framework.permissions.IsAdminUser', # 仅管理员 ) }
-
2, 局部配置
class BookInfoView(ModelViewSet): ... # 2,权限 permission_classes = (AllowAny, )
-
注意点:
- 如果设置了全局,局部。那么则使用局部的权限
-
3,限流Throttling
-
操作流程:
-
1,全局的配置
REST_FRAMEWORK = { ... # 3,限流 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '3/minute', 'user': '5/minute' } }
-
2,局部
class BookInfoView(ModelViewSet): ... # 只对匿名用户限流 throttle_classes = (AnonRateThrottle, ) class TestThrottleView(APIView): def get(self, request): return Response('test....')
-
注意点
- 如果设置了全局,局部。那么则使用局部限流
-
4, 可选限流
-
操作流程:
-
1,全局配置
REST_FRAMEWORK = { ... # 可选配置 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.ScopedRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'downloads': '10/minute', 'uploads': '5/minute' } }
-
2,在视图中使用
# 书籍 class BookInfoView(ModelViewSet): ... # 可选限流(user_id, ip) throttle_scope = 'downloads' # 10/minute class TestThrottleView(APIView): throttle_scope = 'uploads' # 5/minute def get(self, request): return Response('test....')
-
5,分页Pagination
-
操作流程:
-
1,全局配置
REST_FRAMEWORK = { ... # 4, 分页 # 页数的方式: ?page=2 # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', # 偏移量的方式: ?limit=3&offset=3 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 2 # 每页数目 }
-
2,局部配置
# 书籍 class BookInfoView(ModelViewSet): ... # 4,分页 from rest_framework.pagination import PageNumberPagination pagination_class = PageNumberPagination
-
6, 自定义分页类
-
操作流程:
-
自定义类
class MyPageNumberPagination(PageNumberPagination): # 1,设置分页大小 page_size = 3 # 2.允许客户端使用参数控制分页大小 page_size_query_param = 'page_size' # 3,设置页面最大值 max_page_size = 4
-
使用
# 书籍 class BookInfoView(ModelViewSet): ... # 自定义分页类 pagination_class = MyPageNumberPagination
-
7,过滤Filtering
-
操作流程
-
1,安装django-filter
pip insall django-filter
-
2,注册子应用
INSTALLED_APPS = [ ... 'django_filters', ]
-
3,设置配置
REST_FRAMEWORK = { ... # 5,过滤 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',) }
-
4,设置过滤的字段(views.py)
class BookInfoView(ModelViewSet): ... # 5,过滤 filter_fields = ('id', 'btitle')
-
访问格式: ?id=1
-
8,排序OrderingFilter
-
操作流程
from rest_framework.filters import OrderingFilter class BookInfoView(ModelViewSet): ... # 6,排序 filter_backends = (OrderingFilter, ) # 访问格式: ordering=字段 升序 ordering=-字段 ordering_fields = ('id', 'bread')
-
注意事项:
- 1,OrderingFilter来自from rest_framework.filters
- 2,浏览器使用, ordering=字段
9,异常处理Exceptions
-
目的:知道drf系统中能够处理的异常,以及不能处理的异常能够重写后也能处理
-
操作流程:
-
1,自定义异常方法
def custom_exception_handler(exc, context): # 1.先调用drf的异常处理函数 response = exception_handler(exc, context) # 2.如果response is None 表示 drf不能处理的异常,添加自己的逻辑 if response is None: response = Response(str(exc), status=status.HTTP_500_INTERNAL_SERVER_ERROR) # 3.返回响应 return response
-
2,添加异常处理方法到配置中
REST_FRAMEWORK = { ... # 6,异常 'EXCEPTION_HANDLER': 'booktest.myexceptions.custom_exception_handler' }
-
3,在视图中测试
class TestThrottleView(APIView): throttle_scope = 'uploads' # 5/minute def get(self, request): from rest_framework.exceptions import APIException from rest_framework.views import exception_handler # 抛出异常,系统能处理的 # raise APIException('系统能处理的异常') # 系统不能处理的异常 raise ZeroDivisionError('0除错误') return Response('test....')
-
10,接口文档
-
操作流程:
-
1,安装
- pip install coreapi
-
2,添加路由(source_code/urls.py)
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^booktest/', include('booktest.urls')), url(r'^docs/', include_docs_urls(title='天书')), ] # 如果报错,就添加一下配置 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
-
3,字段说明信息调整
- a.模型类字段中添加help_text
- b.序列化器中使用extra_kwargs 添加help_text约束
# 书籍的序列化器 class BookInfoModelSerializer(serializers.ModelSerializer): class Meta: model = BookInfo fields = '__all__' extra_kwargs = { 'btitle':{ 'help_text': '书籍' } }
-
4,对视图方法添加注释说明
class BookInfoView(ModelViewSet): """ list: 获取所有书籍数据 create: 添加一本书籍 """
-