![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6beb2b01925aa6c789ebb3f380bc24ff.png)
一、 认证Authentication
1.1 自定义认证类
1.1.1 表模型
class User(models.Model):
username=models.CharField(max_length=32)
password=models.CharField(max_length=32)
class UserToken(models.Model):
user=models.OneToOneField(to='User',on_delete=models.CASCADE)
token=models.CharField(max_length=64)
1.1.2 登录视图
class UserView(APIView):
def post(self, request, *args, **kwargs):
res = {
'code': 100, 'msg': None}
username = request.data.get('username')
password = request.data.get('password')
user = models.User.objects.filter(username=username, password=password).first()
if user:
token = str(uuid.uuid4())
models.UserToken.objects.update_or_create(defaults={
'token': token}, user=user)
res['msg'] = '登录成功'
res['token'] = token
else:
res['code'] = '101'
res['msg'] = '用户名或密码错误'
return Response(res)
1.1.3 路由
urlpatterns = [
path('login/', views.UserView.as_view()),]
1.1.4 认证类的编写
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from . import models
class LoginAuth(BaseAuthentication):
def authenticate(self, request):
token=request.query_params.get('token')
user_token=models.UserToken.objects.filter(token=token).first()
if user_token:
'''
如果返回user,token,后面视图类中通过request对象,可以取到当前登录用户
'''
return
else:
raise AuthenticationFailed('您没有登录,认证失败')
class BookView(ViewSetMixin,ListAPIView):
authentication_classes = [LoginAuth,]
1.1.5 注意
如需自定义认证,需继承一个rest_framework.authentication.BaseAuthentication,重写authenticate,如果认证通过,返回空或两个值,第一个值给request.user
def authenticate