1. 程式人生 > >Django rest_framework----認證,許可權,頻率元件

Django rest_framework----認證,許可權,頻率元件

認證

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from api.models import *

class AuthToken(BaseAuthentication):
    def authenticate(self, request):
        token=request.GET.get('token')
        token_obj=Token.objects.filter(token=token)

        
if token_obj: return token_obj.user,token_obj else: raise AuthenticationFailed('驗證失敗')

 

全域性使用settings配置

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

 

區域性使用,只需要在檢視類里加入:

authentication_classes 
= [TokenAuth, ]


許可權

class SVIPPermission(object):
  message="只有超級使用者才能訪問"
  def has_permission(self,request,view):
    username=request.user
    user_type=User.objects.filter(name=username).first().user_type

    if user_type==3:

      return True # 通過許可權認證
    else:
      return False