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')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值