day-86drf
频率组件
settings.py
REST_FRAMEWORK = { # 自定义频率类 'DEFAULT_THROTTLE_CLASSES': [], 'DEFAULT_THROTTLE_RATES': { 'user': '3/min', #系统频率,现在登录用户和游客 'anon': '3/min', #只限制游客 'time_rate': '3/min', #自定义频率 }, }
自定义频率类(需要对游客非IP限制条件才需要自定义类):
from rest_framework.throttling import SimpleRateThrottle class TimeRateThrottle(SimpleRateThrottle): scope = 'time_rate' def get_cache_key(self, request, view): if request.user: # 登陆用户 return 'throttle_%s_%s' % (request.user.username, request.user.pk) return 'throttle_time_rate' # 游客,可以从request.META中取出IP等信息作为限制,用法同上 # rate = '3/min' #第二种自定义频率类 # def get_cache_key(self, request, view): # return 'throttle_time_rate'
视图层:
from rest_framework.viewsets import ModelViewSet from . import models, serializers from rest_framework.response import Response from . import permissions from rest_framework.permissions import IsAuthenticated from rest_framework_jwt.authentication import JSONWebTokenAuthentication from api.authentications import JWTAuthentication from . import throttles from rest_framework import throttling from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import SearchFilter, OrderingFilter from . import paginations class CarsModelViewSet(ModelViewSet): # throttle_classes = [throttles.TimeRateThrottle] # 自定义频率控制 # throttle_classes = [throttling.AnonRateThrottle] # 系统频率控制,只限制游客 # throttle_classes = [throttling.UserRateThrottle] # 系统频率控制,登陆用户通过用户pk限制,游客通过ip限制 queryset = models.Car.objects.filter(is_delete=False) serializer_class = serializers.CarsModelSerializer
过滤(django-filter)、筛选、排序、分页
安装:pip3 install django-filter
注册:
view视图
from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import SearchFilter, OrderingFilter from . import paginations class CarsModelViewSet(ModelViewSet): # 过滤 # 接口:/api/cars/?price=900000&brand=1 filter_backends = [DjangoFilterBackend] filter_fields = ('brand', 'price') # 一般过滤字段为分类字段 # 筛选 # 接口:/api/cars/?search=9&price=900000 #代表9在name或price两个字段进行模糊查询,后面的同上 filter_backends = [DjangoFilterBackend, SearchFilter] search_fields = ('name', 'price') # 排序 # 接口:/api/cars/?ordering=-id | /api/cars/?ordering=-price filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] ordering_fields = ('id', 'price') # 分页:配置一个类,不是类们(列表) pagination_class = paginations.PageNumberPagination pagination_class = paginations.LimitOffsetPagination pagination_class = paginations.CursorPagination
分页的配置类
from rest_framework import pagination class PageNumberPagination(pagination.PageNumberPagination): # 一页的条数 page_size = 2 # 接口中选页码的字段名 - 一般不做修改 - ?page=1 page_query_param = 'page' # 用户可以通过接口自定义一页条数 - ?page=1&page_size=一页的条数 page_size_query_param = 'page_size' # 用户可以自定义的最大一页条数,超过就采用最大值 max_page_size = 4 # 接口:?offset=0&limit=3 从(从头偏移0条)第1条往后查3条 class LimitOffsetPagination(pagination.LimitOffsetPagination): # 一页的条数 default_limit = 2 limit_query_param = 'limit' offset_query_param = 'offset' # 用户可以自定义的最大一页条数,超过就采用最大值 max_limit = 4 class CursorPagination(pagination.CursorPagination): # 一页的条数 page_size = 2 # 请求页码数据的字段 - 字段后的参数是加密的 cursor_query_param = 'cursor' # 用户自定义一页条数的字段与最大值 page_size_query_param = 'page_size' max_page_size = 4 # 默认数据查询的排序条件 - 不能与drf的ordering组件同时使用 ordering = '-id'
drf自定义异常模块:drf没有提供处理的服务器异常
settings:
REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'api.exceptions.exception_handler', }
自定义类:
from rest_framework.response import Response from rest_framework.views import exception_handler as drf_exception_handler from rest_framework import status def exception_handler(exc, context): exception = exc view = context.get('view') args = context.get('args') kwargs = context.get('kwargs') request = context.get('request') response = drf_exception_handler(exc, context) if response is None: return Response('服务器错误', status=status.HTTP_500_INTERNAL_SERVER_ERROR) response.data = { 'status': 1, 'msg': response.data['detail'] } return response
接口文档
http://yapi.demo.qunar.com/#