### 1.功能组件 ```python from rest_framework.authentication import BaseAuthentication # 认证 from rest_framework.permissions import BasePermission # 权限 from rest_framework.throttling import BaseThrottle # 节流 from rest_framework.pagination import PageNumberPagination # 分页 from rest_framework.pagination import LimitOffsetPagination from django_filters.rest_framework.backends import DjangoFilterBackend # 过滤 from rest_framework.filters import OrderingFilter # 排序 ``` #### 1.认证 ```python REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication' ), } # 局部配置: class UserAPIView(GenericAPIView): authentication_classes = (..., ...) ``` #### 2.权限 ```python # 全局配置(settings.py): REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), } # 局部配置: class UserAPIView(GenericAPIView): permission_classes = (..., ...) ``` #### 3.限流 ```python # 全局配置(settings.py): REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( ), 'DEFAULT_THROTTLE_RATES': { 'user': '100/day', # second, minute, hour, day 'anon': '10/day', }, } # 局部配置: class UserAPIView(GenericAPIView): throttle_classes = (..., ...) ``` ##### 可选限流: ```python from rest_framework.throttling import ScopedRateThrottle REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.ScopedRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'download': '10/day' } } class UserAPIView(GenericAPIView): throttle_scope = 'download' ``` #### 4.分页 ```python # 全局配置(settings.py): REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': ( ), PAGE_SIZE: 10, } # 局部配置: class UserAPIView(GenericAPIView): pagination_class = LimitOffsetPagination/PageNumberPagination LimitOffsetPagination # .../?page=2&offset=3 # page 指定页数, offset指定偏移量 从offset起显示第page页, 每页page_size个数据 PageNumberPagination # .../?page=2&page_size=3 # page 指定页数, 第page页, 每页page_size个数据 ``` ##### 自定义分页: ```python class UserPage(PageNumberPagination): page_query_param = 'page_size' # 指定page_size参数, 默认即为page_size max_page_size = 10 # 每页最大显示条数 class UserAPIView(GenericAPIView): pagination_class = UserPage # .../?page=2&page_size=3 class CatePagination(PageNumberPagination): page_query_param = 'pagenum' page_size_query_param = 'pagesize' page_size = 2 page_num = 1 max_page_size = 10 def get_paginated_response(self, data): return Response({ 'count': self.page.paginator.count, # 数据总数 'datas': data, # 当前页集 'page': self.page.number, # 第*页 'pages': self.page.paginator.num_pages, # 总页数 'pagesize': self.request.query_params.get('pagesize') or self.max_page_size, # 当前页数据量 # ('next', self.get_next_link()), # ('previous', self.get_previous_link()), }) """ page_query_param = 'pagenum' page_size_query_param = 'pagesize' 指定前端传递的参数 重写get_paginated_response(self, data)方法 data 是分页的页集 """ ``` #### 5.过滤 ```python pip install django-filters # 在settings.py中注册 'django_filters' # 全局配置(settings.py): REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.backends.DjangoFilterBackend' ), } # 局部配置: class UserAPIView(GenericAPIView): filter_backends = (DjangoFilterBackend, ), filter_fields = ['name', 'email'], # .../?name=xs&emain=1 # 精确查找 ``` #### 6.排序 ```python # 配置: class UserAPIView(GenericAPIView): filter_backends = [OrderingFilter] ordering_fields = ['name', 'email'], # .../?ordering=-name, email # name逆序, 相同按email正序 ``` #### 7.异常 ```python # utils/bkexceptions.py # 自定义异常 # encoding=utf-8 from django.db import DatabaseError from rest_framework.views import exception_handler def bk_exception_handler(exc, context): response = exception_handler(exc, context) # 如果是APIEexception及其子类的异常都会被捕捉, 其他异常response将为None if response is not None: response.data['status_code'] = response.status_code return response if isinstance(exc, DatabaseError): response = { 'data': { 'status': 500, 'msg': '数据库异常' } } elif isinstance(exc, Exception): pass return response # settings.py REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'bk.utils.bkexceptions.bk_exception_handler' } ```
浙公网安备 33010602011771号