回顾
1 频率限制
-写一个类,继承SimpleRateThrottle,重写get_cache_key,返回什么就以什么做限制(限制ip,限制用户id,手机号),写一个类属性scop='字符串',需要跟配置文件中对应 '字符串':'5/m'
-局部配置,全局配置
2 过滤和排序
-过滤类:SearchFilter
-排序类: OrderingFilter
-配置在继承GenericAPIView+ListModelMixin及其子类,类属性:filter_backends
-配置相应的字段
-search_fields=['name']
-ordering_fields = ['price']
3 第三方过滤类
-配置在类属性上:filter_backends = [DjangoFilterBackend]
-配置字段:filterset_fields=['name','price']
-http://127.0.0.1:8000/books/?name=红楼梦&price=12
4 自定义过滤类
-自己写一个类,继承BaseFilterBackend,重写filter_queryset,返回qs对象,qs是过滤后的
-配置在继承GenericAPIView+ListModelMixin及其子类,类属性:filter_backends
5 分页功能
-三个分页类
PageNumberPagination:基本分页 ?page=1&size=2
-四个类属性
LimitOffsetPagination:偏移分页 ?limit=3&offset=2
-四个类属性
CursorPagination:游标分页 选择上一页和下一页
-三个类属性
-cursor_query_param = 'cursor'
-page_size = 2
-ordering = 'id'
-只需要配置在继承GenericAPIView+ListModelMixin及其子类,类属性:pagination_class
6 drf处于的位置:路由匹配成功,进视图类之前
-包装了新的request
-处理了编码(urlencoded,formdata,json)
-三大认证(*****)
-进了视图类 :(GenericAPIView+ListModelMixin)(*****)
-进行了过滤和排序
-去模型中取数据
-分页
-序列化(*****)
-返回
-处理了响应(浏览器,json)
-处理了全局异常
今日内容
1 认证,频率,权限(**
)
1.1 认证源码
def perform_authentication(self, request):
request.user
@property
def user(self):
if not hasattr(self, '_user'):
with wrap_attributeerrors():
self._authenticate()
return self._user
def _authenticate(self):
for authenticator in self.authenticators:
try:
user_auth_tuple = authenticator.authenticate(self)
except exceptions.APIException:
self._not_authenticated()
raise
if user_auth_tuple is not None:
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple
return
self._not_authenticated()
-是在Request初始化的时候,传入的
-Request类是在什么时候初始化的---》APIView的dispatch中的刚开始位置
-APIView的dispatch---》request = self.initialize_request(request, *args, **kwargs)
def initialize_request(self, request, *args, **kwargs):
return Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(),
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)
def get_authenticators(self):
return [auth() for auth in self.authentication_classes]
1.2 频率源码
def check_throttles(self, request):
throttle_durations = []
for throttle in self.get_throttles():
if not throttle.allow_request(request, self):
throttle_durations.append(throttle.wait())
def get_throttles(self):
return [throttle() for throttle in self.throttle_classes]
1.3 权限源码
def check_permissions(self, request):
for permission in self.get_permissions():
if not permission.has_permission(request, self):
self.permission_denied(
request,
message=getattr(permission, 'message', None),
code=getattr(permission, 'code', None)
)
def get_permissions(self):
return [permission() for permission in self.permission_classes]
-在权限类中配置message即可(给对象,类都可以)
2 自定义全局异常(****
)
def common_exception_handler(exc, context):
response = exception_handler(exc, context)
if response:
return Response(data={'code': 9998, 'msg': response.data})
else:
return Response(data={'code': 9999, 'msg': '服务器异常,请联系系统管理员'})
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'app01.exceptions.common_exception_handler',
}
3 自动生成接口文档(**
)
-前端一批人
-根本不知道你写了什么接口,请求参数什么样,响应数据什么样
-使用什么编码都不知道
-后端一批人
-我们写了很多接口
-1 公司有接口文档平台,后端在平台上录入接口
-2 使用第三方接口文档平台,后端写了在平台录入
-Yapi:开源
-3 使用md,word文档写,写完传到git上
-4 自动生成接口文档(swagger,coreapi)
-swagger自动导入,导入到Yapi中
-pip3 install coreapi
-在路由中配置
path('docs/', include_docs_urls(title='路飞项目接口文档平台'))
-在配置文件中配置
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
-访问地址http://127.0.0.1:8000/docs(只要路由中有的,都能看到)