drf之认证

认证类(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 = []
  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值