RSETFul登陸驗證

首先查看我的工程目錄(因爲測試,所以命名不規範,還打錯了。。。):
工程目錄
全局配置和局部配置略有不同:
局部,需要驗證的寫:寫在views.py中

from App.models import *
from rest_framework.authentication import BaseAuthentication #驗證的基類
from rest_framework import exceptions

class Auth(BaseAuthentication):	#這裏要繼承,如果直接繼承object則需要寫兩個方法,
    def authenticate(self,request):
        token = request._request.GET.get('token') #原request被重寫,所以使用request._request
        print(token)
        token = Token.objects.filter(token=token).first()
        if token:
            print(token)
            return (token.user,token)	#返回元組,第一個值給request.user,第二個值給request.auth
        else:
            raise exceptions.AuthenticationFailed('你沒登陸')#拋出自定義異常

class Cart(APIView):
    authentication_classes = [Auth,]	#是個列表,會一個一個訪問是否驗證,需要驗證的加這一行,給出驗證類即可

    def post(self,request, *args, **kwargs):
        print('----',request.user.username)	#這兩個輸出使用上面元組賦值的對象
        print(request.auth.token)		#user和token是兩個OneToOne關係表
        return HttpResponse('你訪問到了')

全局設置驗證,局部不嚴驗證:
auth.py中寫上驗證類:

from App.models import *
from rest_framework.authentication import BaseAuthentication #驗證的基類
from rest_framework import exceptions

class Auth(BaseAuthentication):	#這裏要繼承,如果直接繼承object則需要寫兩個方法,
    def authenticate(self,request):
        token = request._request.GET.get('token') #原request被重寫,所以使用request._request
        print(token)
        token = Token.objects.filter(token=token).first()
        if token:
            print(token)
            return (token.user,token)	#返回元組,第一個值給request.user,第二個值給request.auth
        else:
            raise exceptions.AuthenticationFailed('你沒登陸')#拋出自定義異常

settings.py:在最後加

RSET_FRAMEWORK={
    'DEFAULT_AUTHENTICATION_CLASSES' : ['App.auth.auth.Auth',],
    'UNAUTHENTICATED_USER':None,	#設置之後沒有request.user會返回None而不是AnonymousUser
    'UNAUTHENTICATED_TOKEN':None
}

view.py:

class Login(APIView):
    authentication_classes = [] #局部不驗證設置爲空即可
    def post(self, request, *args, **kwargs):
        #self.dispatch,如何驗證,配置信息都在dispatch中可以找到,
        print(request.user) #沒有則返回None,未設置則返回AnonymousUser
        print(request.auth)	#沒有則返回None
        try:
            user = request._request.POST.get("username") #request被重寫,當然原來的方法也可以用,可以不需要_request,還是遵循rsetful風格吧
            pwd = request._request.POST.get("password")
            users = User.objects.filter(username=user,password=pwd).first()
            if users:
                token = user	#簡單寫一下,可以加密使用
                Token.objects.update_or_create(user=users,defaults={'token':token})#有就跟新,沒有就添加
                return HttpResponse(user)
            return HttpResponse('no')
        except:
            return HttpResponse('except')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章