Certification authority frequency control components

rest_framework components

Certified Components

Local certification

Plus authentication_classes authentication is required in view of the class = [1 based authentication component, the authentication component class 2 ....]

Note : This category should be placed in a separate file py, (if placed in view, the global configuration can not be used)

Verified (Boolean), can return two values, the request.user a given, one for the request.auth

choice of usage:
- to come up with the number corresponding Chinese: get_ field name _dispaly ()

Examples are as follows:

seralizers.py

from rest_framework import serializers
from app01 import models
 
class PublishSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.Publish
        fields = '__all__'

auth.py

from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
from app01 import models
 
class TokenAuth(BaseAuthentication):
    def authenticate(self,request):
        '''authenticate'''
        # 验证条件根据需求设置(此示例为需要有token值)
        token = request.GET.get('token')
        token_obj = models.Token.objects.filter(token=token).first()
        if not token_obj:
            # 如果验证失败,需抛出AuthenticationFailed异常
            raise exceptions.AuthenticationFailed("验证失败!")
        else:
            user = token_obj.user
            # 如果验证成功,需要返回一个元组,分别是用户以及验证类的实例对象,然后源码内会赋值给request.user和request.auth
            return user,token_obj

views.py

def get_random(name):
    import hashlib
    import time
    md=hashlib.md5()
    md.update(bytes(str(time.time()),encoding='utf-8'))
    md.update(bytes(name,encoding='utf-8'))
    return md.hexdigest()
class Login(APIView):
    def post(self,reuquest):
        back_msg={'status':1001,'msg':None}
        try:
            name=reuquest.data.get('name')
            pwd=reuquest.data.get('pwd')
            user=models.User.objects.filter(username=name,password=pwd).first()
            if user:
                token=get_random(name)
                                                                                      models.UserToken.objects.update_or_create
                    (user=user,defaults={'token':token})
                back_msg['status']='1000'
                back_msg['msg']='登录成功'
                back_msg['token']=token
            else:
                back_msg['msg'] = '用户名或密码错误'
        except Exception as e:
            back_msg['msg']=str(e)
        return Response(back_msg)


class Course(APIView):
    authentication_classes = [TokenAuth, ]

    def get(self, request):
        return HttpResponse('get')

    def post(self, request):
        return HttpResponse('post')

Global Certification

As follows in settings.py

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": ["app01.auth.TokenAuth",]
}

After this configuration, each class must view after successful authentication through to the next step,

If there is some method does not require authentication, such as login function needs to be added separately in this view a configuration properties:

authentication_classes = [] #将自身的认证类置空

Certification authority

Local certification

permission.py

from rest_framework.permissions import BasePermission
class UserPermission(BasePermission):
    message = '不是超级用户,查看不了'
    def has_permission(self, request, view):
        # user_type = request.user.get_user_type_display()
        # if user_type == '超级用户':
        user_type = request.user.user_type
        print(user_type)
        if user_type == 1:
            return True
        else:
            return False

views.py

class Course(APIView):
    authentication_classes = [TokenAuth, ]
    permission_classes = [UserPermission,]

    def get(self, request):
        return HttpResponse('get')

    def post(self, request):
        return HttpResponse('post')

If the certification authority by this time, it will continue to the next step, if it is not passed, it will return an error message, as follows:

{"detail":"You do not have permission to perform this action."}

Topical use only need to add in the view class:

permission_classes = [UserPermission,][]

If desired custom error messages, only you need to define a message property to the view class, as follows:

message="只有超级用户才能访问"

Global Certification

REST_FRAMEWORK = {
    # 认证组件
    "DEFAULT_AUTHENTICATION_CLASSES": ["app01.auth.TokenAuth",],
    # 权限组件
    "DEFAULT_PERMISSION_CLASSES": ["app01.permission.VipPermission",],
}

Frequency Certification

In order to control the frequency of a user request url, for example, less than a minute, only three access (throttled Access Control)

Local certification

Package

class MyThrottle(SimpleRateThrottle):
            scope='aaa'
            def get_cache_key(self, request, view):
                return self.get_ident(request)
                # 返回什么就以什么来作为次数限制对象

view

class CourseView(ModelViewSet):
    authentication_classes = [self_authentication.UserAuthentication]
    permission_classes = [self_permissions.AdminPermission]
    throttle_classes = [self_throttle.LookUpCourseRateThrottle]
    queryset = models.Course.objects.all()
    serializer_class = self_serializers.CourseSerializers
    # 自定义提示信息
    def throttled(self, request, wait):
        from rest_framework import exceptions

        class MyThrottled(exceptions.Throttled):
            default_detail = '下次访问'
            extra_detail_singular = '还剩 {wait} 秒.'
            extra_detail_plural = '还剩 {wait} 秒'

        raise MyThrottled(wait)

 Then add the following classes are to be arranged in view of restrictions:

throttle_classes = [VisitRateThrottle]

In the setting of:

REST_FRAMEWORK = {
                'DEFAULT_THROTTLE_RATES':{
                    'aaa':'10/m'
                }
            }

Global Use

- written in the setting of

'DEFAULT_THROTTLE_CLASSES':['app01.self_throttle.LookUpCourseRateThrottle',],

If you do not need to write only in the view in a view

    throttle_classes = [] # 将自身的认证类置空

Display error message into Chinese (the view shown above)

def throttled(self, request, wait):
                class MyThrottled(exceptions.Throttled):
                    default_detail = '傻逼'
                    extra_detail_singular = '还剩 {wait} 秒.'
                    extra_detail_plural = '还剩 {wait} 秒'

                raise MyThrottled(wait)

Guess you like

Origin www.cnblogs.com/9527mwz/p/11200588.html