Fork me on GitHub

综合使用 认证,权限,限流

方法总结

认证

	类 authenticate/authenticate_header
	返回值 None,(user,auth),异常
	配置 
		视图
		全局

权限 
	
	类 has_permission/has_object_permission
	返回值 True,False,exceptoions.PermissionDenied(detail='error')
	配置 
		视图
		全局

限流

	类 allow_request/wait 'scope = "" '
	返回值 True False

	配置 
		视图
		全局

代码

认证

class MyAuthentication(BaseAuthentication):
    def authenticate(self,request):
        token = request.query_params.get('token')
        if token == 'abc':
            return ('ale','auth')
        # raise APIException('认证失败')
        # raise NotAuthenticated('认证失败')
        return None

    def authenticate_header(self, request):
        pass

限流

class AnonyThrottle(SimpleRateThrottle):
    scope = 'WDP_ANONNY'  # 配置 'DEFAULT_THROTTLE_RATES':{'WDP':'3/m'}
    def get_cache_key(self, request, view):
        if request.user:
            return None
        return self.get_ident(request)  #  设置 ip 为 cache记录的 key

class UserThrottole(SimpleRateThrottle):
    scope = 'WDP_USER'
    def get_cache_key(self, request, view):
        if request.user:
            return request.user
        return None

class VIPThrottole(SimpleRateThrottle):
    scope = 'WDP_VIP'
    def get_cache_key(self, request, view):
        if request.user and request.user == 'ale':
            return request.user
        return None

权限

class MyPermission(object):
    message = '无权访问'
    def has_permission(self,request,view):
        if request.user == 'userAdmin' or request.user == 'ale':
            return True
        return False

settings

REST_FRAMEWORK = {
    'UNAUTHENTICATED_USER':None,
    'UNAUTHENTICATED_TOKEN':None,
    'DEFAULT_AUTHENTICATION_CLASSES':[
        'goods.utils.MyAuthentication'
    ],
    'DEFAULT_THROTTLE_RATES':{
        'WDP_ANONNY':'1/m',
        'WDP_USER':'5/m',
        'WDP_VIP':'10/m',

    }
}

视图

# 不需要登录就可以访问 + 限流
class IndexView(APIView):
    # authentication_classes =
    permission_classes =  []
    throttle_classes = [AnonyThrottle,UserThrottole,VIPThrottole]
    def get(self,request,*args,**kwargs):
        return JsonResponse(u'主页',safe=False)

# 需要登录权限验证 + 限流
class GoodsListView(APIView):
    #
    # 先 登录认证 authentication_classes = [Myauthentication,]
    # 不同等级的权限 依次 验证  permission_classes = [userPermission,adminPermission]
    permission_classes = [MyPermission,]
    # authentication_classes = []
    throttle_classes = [AnonyThrottle,UserThrottole,VIPThrottole]

    def get(self,request,*args,**kwargs):
        goods = Goods.objects.all()
        goods_serializer = GoodsSerializer(goods,many=True)
        return Response(goods_serializer.data)
posted @ 2018-03-01 21:41  派对动物  阅读(256)  评论(0编辑  收藏  举报
Top