rest_framework認證,頻率,許可權
阿新 • • 發佈:2019-01-04
在views中 from rest_framework.views import APIView from rest_framework.viewsets import ViewSetMixin import hashlib import time from app01 import models from rest_framework.response import Response from django.http import JsonResponse class Login(ViewSetMixin,APIView): def get_token(self): h5=hashlib.md5() ctime=time.time() h5.update(bytes(str(ctime),encoding='utf-8')) token=h5.hexdigest() return token def ulogin(self,request): response={'status':100,'msg':'登入成功'} name=request.data.get('name') pwd=request.data.get('pwd') user=models.UserInfo.objects.all().filter(name=name,pwd=pwd).first() if user: ret=models.UserToken.objects.all().create(token=self.get_token(),user=user)#登入成功就去資料庫中寫token response['token']=self.get_token() else: response['status']=101 response['msg']='使用者名稱或密碼錯誤' return Response(response) class Author(ViewSetMixin,APIView): #區域性使用登入認證,頻率,許可權 throttle_classes = [MyThrottle, ] authentication_classes = [LoginAuth, ] permission_classes = [UserPermission,] def get_authors(self,request): author=models.Author.objects.all() ser=Myser.Authorser(author,many=True) return Response(ser.data) #頻率錯誤資訊顯示 def throttled(self, request, wait): class MyThrottled(exceptions.Throttled): default_detail = '×××' extra_detail_singular = '還剩 {wait} 秒.' extra_detail_plural = '還剩 {wait} 秒' 在MyAuth中---------------------------------------------------------------------------------------------------- from app01 import models from rest_framework import exceptions class LoginAuth(): def authenticate(self, request): token = request.query_params.get('token') ret = models.UserToken.objects.all().filter(token=token).first() if ret: return ret.user, ret else: raise exceptions.APIException('認證失敗') class UserPermission(): # message是出錯顯示的中文 message = '您沒有許可權檢視' def has_permission(self, request, view): user_type = request.user.user_type # 取出使用者型別對應的文字 # 固定用法:get_欄位名字_display() user_type_name = request.user.get_user_type_display() print(user_type_name) if user_type == 2: return True else: return False from rest_framework.throttling import SimpleRateThrottle class MyThrottle(SimpleRateThrottle): scope = 'pinglv' def get_cache_key(self, request, view): return self.get_ident(request) 在Myser中--------------------------------------------------------------------------------- from rest_framework import serializers from app01 import models class Bookser(serializers.ModelSerializer): class Meta: model=models.Book fields='__all__' class Authorser(serializers.ModelSerializer): class Meta: model=models.Author fields='__all__' 在setting中----------------------------------------------------------------------------------------- REST_FRAMEWORK = { # 'DEFAULT_AUTHENTICATION_CLASSES':['app01.MyAuth.LoginAuth',],#認證全域性使用 # 'DEFAULT_PERMISSION_CLASSES':['app01.MyAuth.UserPermission',],#許可權全域性使用 # 'DEFAULT_THROTTLE_CLASSES': ['app01.MyAuth.MyThrottle', ],#頻率全域性使用 # 每分鐘訪問10次 'DEFAULT_THROTTLE_RATES': { 'pinglv': '10/m' }, }