认证类(BaseAuthentication)
在上面的视图及路由组件中,我们学会了更快地创建我们想要的接口和自动生成路由。
我们创建一个登录接口,和一个更改图书表的接口,那么该如何先通过登录接口,只有登录了才能进入更改图书表的接口呢:
前提准备:
models.py
from django.db import models
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=64)
password = models.CharField(max_length=64)
class UserToken(models.Model):
token = models.CharField(max_length=64)
user = models.OneToOneField(to='User', on_delete=models.CASCADE)
class Book(models.Model):
name = models.CharField(max_length=64)
price = models.IntegerField()
publish = models.CharField(max_length=32)
views.py
import uuid
from django.shortcuts import render
# Create your views here.
from rest_framework.viewsets import ViewSet
from .models import User,UserToken, Book
from rest_framework.decorators import action
from rest_framework.response import Response
from .serializer import BookSerializer
class UserView(ViewSet):
@action(methods=['POST'], detail=False)
def login(self, request):
username = request.data.get('username')
password = request.data.get('password')
user = User.objects.filter(username=username, password=password).first()
if user:
token = str(uuid.uuid4())
UserToken.objects.update_or_create(defaults={'token':token}, user=user)
return Response({'code': '100', 'msg': '登录成功'})
else:
return Response({'code': '101', 'msg': '账号或密码错误'})
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, CreateModelMixin, DestroyModelMixin
class BookView(GenericViewSet, ListModelMixin, CreateModelMixin, DestroyModelMixin):
queryset = Book.objects.all()
serializer_class = BookSerializer
serializer.py
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
urls.py
from django.urls import path, include
from .views import UserView, BookView
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('users', UserView, 'users')
router.register('books', BookView, 'books')
urlpatterns = [
path('api/v1/', include(router.urls))
]
前提条件已经准备好了,那就开始介绍我们的认证类:BaseAuthentication
根据规范,我们应先创建一个py文件,
然后创建一个认证类并继承BaseAuthemtication
然后重写认证类,先从用户发送的请求头中取出用户的token,然后与数据库中的token进行校验,判断是否登录,然后返回结果,在views.py中只需要导入认证类,输入
authentication_classes = [重写的认证类]
就可以进行认证。
以上配置是局部使用,下面是全局使用:
很简单,就是把drf里面的源码复制到自己的settings文件里,然后加上重写认证类的位置。
但是,全局配置好了会出bug,自己用不了了,需要局部禁用:
只需要在禁用的地方加上:
authentication_classes = []