后端token认证模板

1.创建一个视图

from rest_framework import exceptions
from app01 import models
from rest_framework.authentication import BaseAuthentication


class TokenAuth(BaseAuthentication):
    def authenticate(self, request):
        # 取到 request里面的 token值
        totken = request.GET.get('token')
        token_obj = models.UserToken.objects.filter(token=totken).first()
        if not token_obj:
            # 抛认证字段的异常
            raise exceptions.AuthenticationFailed("验证失败")
        else:
            return token_obj.user.user, token_obj.token

2.view导入使用即可

class MicroView(APIView):
    authentication_classes = [auth.TokenAuth,]
    def get(self,request,*args,**kwargs):
        ret = {'code':1000,'data':'特色课程'}
        return Response(ret)
原文地址:https://www.cnblogs.com/Rivend/p/11988702.html