############### ############### custom token authentication
table
class UserInfo(models.Model): username = models.CharField(max_length=16) password = models.CharField(max_length=32) type = models.SmallIntegerField( choices=((1, '普通用户'), (2, 'VIP用户')), default=1 ) class Token(models.Model): user = models.OneToOneField(to='UserInfo') token_code = models.CharField(max_length=128)
view
DEF get_random_token (username): "" " generate random timestamp token and the user name : param username: : return: " "" Import hashlib, Time timestamp = STR (the time.time ()) m = hashlib.md5 (bytes (username , encoding = " UTF8 " )) m.update (bytes (timestamp, encoding = " UTF8 " )) return m.hexdigest () class the LoginView (APIView): "" " check whether the correct user name and password to generate a token view "" " DEF POST (Self, Request): res = {"code": 0} print(request.data) username = request.data.get("username") password = request.data.get("password") user = models.UserInfo.objects.filter(username=username, password=password).first() if user: # 如果用户名密码正确 token = get_random_token(username) models.Token.objects.update_or_create(defaults={"token_code": token}, user=user) RES [ " token " ] = token the else : RES [ " code " ]. 1 = RES [ " error " ] = " user name or password is incorrect " return the Response (RES)
Certification class
from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed class MyAuth(BaseAuthentication): def authenticate(self, request): if request.method in ["POST", "PUT", "DELETE"]: request_token = request.data.get("token", None) if not request_token: raise AuthenticationFailed('缺少token') token_obj = models.Token.objects.filter(token_code=request_token).first() if not token_obj: raise AuthenticationFailed('无效的token') return token_obj.user.username, None else: return None, None
View level certification
class CommentViewSet(ModelViewSet): queryset = models.Comment.objects.all() serializer_class = app01_serializers.CommentSerializer authentication_classes = [MyAuth, ]
Global level certification
# 在settings.py中配置 REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ["app01.utils.MyAuth", ] }
############### ############### rights
A custom permission class
# Custom permission class MyPermission (BasePermission): the Message = ' VIP users can access the ' DEF has_permission (Self, Request, View): "" " Custom Permissions Only VIP users can access the " "" # because the judge had prior rights made a judgment certified, so here you can directly get request.user IF request.user and request.user.type == 2: # If you are a VIP user return True the else : return False
View-level permissions
class CommentViewSet(ModelViewSet): queryset = models.Comment.objects.all() serializer_class = app01_serializers.CommentSerializer authentication_classes = [MyAuth, ] permission_classes = [MyPermission, ]
Global level permissions:
# Set rest framework settings.py configuration items in the REST_FRAMEWORK = { " DEFAULT_AUTHENTICATION_CLASSES " : [ " app01.utils.MyAuth " ,], " DEFAULT_PERMISSION_CLASSES " : [ " app01.utils.MyPermission " ,] }
############### ############### restrictions
Customize restricted
= VISIT_RECORD {} # custom limit class MyThrottle (Object): DEF the __init__ (Self): self.history = None DEF allow_request (Self, Request, View): "" " Custom frequency limit access to only three times within 60 seconds ." "" # get user IP ip = request.META.get ( " REMOTE_ADDR " ) timestamp = time.time () IF ip not in VISIT_RECORD: VISIT_RECORD [ip] = [timestamp,] return True History= VISIT_RECORD[ip] self.history = history history.insert(0, timestamp) while history and history[-1] < timestamp - 60: history.pop() if len(history) > 3: return False else: return True def wait(self): """ 限制时间还剩多少 """ timestamp = time.time() return 60 - (timestamp - self.history[-1])
View level restrictions
class CommentViewSet(ModelViewSet): queryset = models.Comment.objects.all() serializer_class = app01_serializers.CommentSerializer throttle_classes = [MyThrottle, ]
Global level restrictions
# 在settings.py中设置rest framework相关配置项 REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ["app01.utils.MyAuth", ], "DEFAULT_PERMISSION_CLASSES": ["app01.utils.MyPermission", ] "DEFAULT_THROTTLE_CLASSES": ["app01.utils.MyThrottle", ] }
############### ############### Certification
############### ############### Certification