在須要認證的視圖類里加上authentication_classes = [認證組件1類名,認證組件2類名....]python
示例以下:app
seralizers.py函數
from rest_framework import serializers from app01 import models class PublishSerializers(serializers.ModelSerializer): class Meta: model = models.Publish fields = '__all__'
auth.pythis
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.username,token_obj
views.pyrest
from rest_framework import viewsets from app01.auth import TokenAuth class PublishViewSet(viewsets.ModelViewSet): # 在這裏配置authentication_classes # 注意,值爲一個列表,能夠放多個認證組件類名 authentication_classes = [TokenAuth] queryset = models.Publish.objects.all() serializer_class = serializer.PublishSerializers
在setting.py裏配置以下:orm
REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ["app01.auth.TokenAuth",] }
這樣配置以後,每一個視圖類都要通過認證成功以後才能執行下一步,對象
若是有某些方法不須要認證,如login函數,則須要在login函數中單獨加入一個配置屬性:blog
authentication_classes = [] #本身的類裏有的話就調用此類的配置,爲空既什麼都不作
permission.pytoken
from app01 import models class VipPermission(): def has_permission(self,request,view): # 通過認證組件以後將用戶名賦值給了request.user # 這裏能夠直接取到 username = request.user user = models.User.objects.filter(username=username).first() # 若是用戶的vip值爲1,即爲True,則經過認證,不然return False if user.vip: return True else: return False
views.pyip
from rest_framework import viewsets from app01.auth import TokenAuth from app01.permission import VipPermission class PublishViewSet(viewsets.ModelViewSet): authentication_classes = [TokenAuth] permission_classes = [VipPermission] queryset = models.Publish.objects.all() serializer_class = serializer.PublishSerializers
這個時候若是登陸用戶是vip,則會繼續執行下一步,若是是普通用戶,則會返回錯誤信息,以下:
{"detail":"You do not have permission to perform this action."}
若是須要自定義錯誤信息,只須要在類裏定義一個message屬性便可,以下:
message="只有超級用戶才能訪問"
REST_FRAMEWORK = { # 認證組件 "DEFAULT_AUTHENTICATION_CLASSES": ["app01.auth.TokenAuth",], # 權限組件 "DEFAULT_PERMISSION_CLASSES": ["app01.permission.VipPermission",], }
格式以下:
class VisitRateThrottle(object): def allow_request(self,request,view): # 要求訪問站點的頻率不能超過每分鐘20次等等 if 1: # 若是在限制以內,則返回True return True else: return False
而後在須要進行限制的視圖類中加入以下配置:
throttle_classes = [VisitRateThrottle]