2021-09-07 认证源码,频率源码,权限源码 自定义全局异常 自动生成接口文档

本文深入探讨了Django REST框架中的关键组件,包括认证、频率限制和权限管理的源码分析。首先,介绍了如何自定义认证类,通过Request对象的_authenticate方法进行用户验证。接着,讲解了频率限制的实现,通过继承SimpleRateThrottle类并设置scop来限制特定资源。然后,讨论了权限控制,展示了如何定制权限类并处理权限否认。此外,还提到了过滤、排序、分页功能的配置及自定义。最后,简述了如何设置全局异常处理和自动生成接口文档,以提高开发效率和文档质量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

回顾

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 认证源码

#1  入口---》APIView的dispatch---》认证类的代码self.perform_authentication(request)

# 2 self.perform_authentication(request)
    def perform_authentication(self, request):
        request.user # 新的request对象的user方法
        
# 2 Request类的user方法
    @property
    def user(self):
        if not hasattr(self, '_user'):
            with wrap_attributeerrors():
                self._authenticate()  # 核心就是这句话,是Request的
        return self._user
    
    
# 3 Request类的_authenticate(self)方法
    def _authenticate(self):
        for authenticator in self.authenticators: #self.authenticators是个列表,列表中放了一个个认证类的对象
            try:
                # self是request,所以我们的认证类的authenticate,有两个参数,self给了第二个参数
                user_auth_tuple = authenticator.authenticate(self) # 执行认证类的authenticate方法
            except exceptions.APIException:
                self._not_authenticated()
                raise

            if user_auth_tuple is not None:
                self._authenticator = authenticator
                self.user, self.auth = user_auth_tuple  #解压赋值,后续的requtst对象就有user属性了
                return

        self._not_authenticated()
        
 
# 4 Request类的self.authenticators属性
	-是在Request初始化的时候,传入的
    -Request类是在什么时候初始化的---》APIView的dispatch中的刚开始位置
    -APIView的dispatch---》request = self.initialize_request(request, *args, **kwargs)

    
# 5 APIView的self.initialize_request方法
	def initialize_request(self, request, *args, **kwargs):
        return Request(
            request,
            parsers=self.get_parsers(),
            authenticators=self.get_authenticators(),# APIView
            negotiator=self.get_content_negotiator(),
            parser_context=parser_context
        )
    
# 6 APIView的get_authenticators
    def get_authenticators(self):
        # 列表中放了一个个认证类的对象
        return [auth() for auth in self.authentication_classes]

1.2 频率源码

#1 入口---》APIView的dispatch---》频率类的代码self.check_throttles(request)

# 2 APIView的self.check_throttles(request)
    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())
                
# 3 APIView的self.get_throttles()
       def get_throttles(self):
        return [throttle() for throttle in self.throttle_classes]

1.3 权限源码

#1 入口---》APIView的dispatch---》权限类的代码self.check_permissions(request)

#2 APIView的check_permissions(request)方法
    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)
                )
#3  APIView的self.get_permissions():
    def get_permissions(self):
        # 列表里放了一个个权限类的对象
        return [permission() for permission in self.permission_classes]
    
# 4 权限认证失败,返回中文
	-在权限类中配置message即可(给对象,类都可以)

2 自定义全局异常(****

#1  定义一个函数
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': '服务器异常,请联系系统管理员'})
    
 # 2 在配置文件中配置
REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'app01.exceptions.common_exception_handler', 
}

3 自动生成接口文档(**

# 前后的分离
	-前端一批人
    	-根本不知道你写了什么接口,请求参数什么样,响应数据什么样
        -使用什么编码都不知道
    -后端一批人
    	-我们写了很多接口
        
        
# 需要写接口文档(不同公司有规范)
	-1 公司有接口文档平台,后端在平台上录入接口
    -2 使用第三方接口文档平台,后端写了在平台录入
    	-Yapi:开源
    -3 使用md,word文档写,写完传到git上
    -4 自动生成接口文档(swagger,coreapi)
    	-swagger自动导入,导入到Yapi中

        
# coreapi
	-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(只要路由中有的,都能看到)
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值