zoukankan      html  css  js  c++  java
  • DRF之认证组件、权限组件、频率组件使用方法总结

    认证组件格式:

    from rest_framework.authentication import BaseAuthentication
    from rest_framework.exceptions import APIException
    
    from .models import UserToken
    
    
    # 1、定义认证类
    class UserAuth(BaseAuthentication):
    
        # 所有的认证逻辑都在authenticate
        def authenticate(self, request):
            user_token = request.query_params.get("token")
            # print('request.query_params:',request.query_params)
            # print('request.GET',request.GET)
            #request.query_params和request.GET打印的结果一样
            try:
                token = UserToken.objects.get(token=user_token)
                # 后面权限会用到
                return token.user, token.token
            except Exception:
                raise APIException("没有认证")
    2 、局部使用
    authentication_classes=[UserAuth,MyAuth2]
    #注意:当有多个认证类时,返回值必须写在最后一个认证类中
    3 、全局使用
    查找顺序:自定义的APIView里找---》项目settings里找---》内置默认的
    REST_FRAMEWORK={
                'DEFAULT_AUTHENTICATION_CLASSES':['utils.common.UserAuth',]
    
            }

     权限组件格式:

    #1 写一个类
            class MyPermission():
                def has_permission(self,request,view):
                    token=request.query_params.get('token')
                    ret=models.UserToken.objects.filter(token=token).first()
                    if ret.user.type==2:
                    # 超级用户可以访问
                        return True
                    else:
                        return False
    #2 局部使用:
            permission_classes=[MyPermission,]
    #3 全局使用:
                REST_FRAMEWORK={
                'DEFAULT_PERMISSION_CLASSES':['utils.common.MyPermission',]
            }

     频率组件格式:

        1 写一个类:
            from rest_framework.throttling import SimpleRateThrottle
            class VisitThrottle(SimpleRateThrottle):
                scope = 'xxx'    #全局用scope,局部的可以用rate='5/s',如果用rate就不需要在settings里面配置
                def get_cache_key(self, request, view):
                    return self.get_ident(request)
        2 在setting里配置:
                'DEFAULT_THROTTLE_RATES':{
                    'xxx':'5/h',
                }
        3 局部使用
            throttle_classes=[VisitThrottle,]
        4 全局使用
            REST_FRAMEWORK={
                'DEFAULT_THROTTLE_CLASSES':['utils.common.MyPermission',]
            }
  • 相关阅读:
    力扣 136. 只出现一次的数字
    剑指 Offer 24. 反转链表
    javaWeb8——jdbc总结,JDBC调用存储过程和存储函数:CallableStatement
    剑指 Offer 53
    剑指 Offer 53
    使用 .NET Core 3.x 构建 RESTFUL Api
    SqlServer 多表连接、聚合函数、模糊查询、分组查询应用总结(回归基础)
    SqlServer 查询的几种方式以及数字函数、时间函数的应用总结(回归基础)
    关于SqlServer表结构 2(回归基础)
    关于SqlServer那些事1(回归基础)
  • 原文地址:https://www.cnblogs.com/fengchong/p/10100536.html
Copyright © 2011-2022 走看看