rest_framework06:自动生成路由\action使用\认证

自动生成路由

# 1.导入routers模块
from rest_framework import routers

# 2.实例化类
router=routers.SimpleRouter()

# 3.注册
# ('前缀','继承自ModelViewSet视图类','别名')
router.register('books7',views.BooksView) # 不要加斜杠

# 4.加入
urlpatterns+=router.urls

action使用

装时期,给ModelViewSet的试图类,自定义函数,以及路由。

# action 用法
from rest_framework.decorators import action
class BookViewSet(ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookModelSerializer

    # methods 第一个参数,传一个列表,列表中放请求方式
    # ‘/books/get_1’ 是请求地址。books是ModelViewSet 注册的路由
    # detal:True是, 带pk ,即/books/1/get_1
    @action(methods=['GET','POST'],detail=False)
    def get_1(self,request):
        book=self.get_queryset()[:2]
        ser=self.get_serializer(book,many=True)
        return Response(ser.data)

认证

局部认证

1.新写认证类

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

class MyAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 认证逻辑, 如果认证通过,返回两个值
        # 如果认证失败,抛出AuthenticationFailed异常
        token=request.GET.get('token')
        if token:
            user_token=UserToken.objects.filter(token=token).first()
            if user_token:
                return user_token.user,token
            else:
                raise AuthenticationFailed('认证失败')
        else:
            raise AuthenticationFailed('请求地址需要带token')

2.认证逻辑,如使用token,数据库储存。

models.py

class User(models.Model):
    username=models.CharField(max_length=32)
    password=models.CharField(max_length=32)
    user_type=models.IntegerField(choices=((1,'超级用户'),(2,'普通用户'),(3,'二笔用户')))

class UserToken(models.Model):
    token=models.CharField(max_length=64)
    user=models.OneToOneField(to=User,on_delete=models.CASCADE)

views.py

登录功能

# 认证功能
from app01 import models
import uuid

class LoginView(APIView):
    def post(self,request):
        myRespone=MyResponse()
        username=request.data.get('username')
        password=request.data.get('password')
        print(username,password)
        user=models.User.objects.filter(username=username,password=password).first()
        if user:
            # 登陆成功,生成一个随机及付出
            token=uuid.uuid4()
            # 查询,没有就新增
            models.UserToken.objects.update_or_create(defaults={'token':token},user=user)
            myRespone.msg='登陆成功'
            myRespone.token=token
        else:
            myRespone.status=101
            myRespone.msg='用户名或密码错误'
        return Response(myRespone.get_dic)

视图类

增加authentication_classes

from rest_framework.viewsets import ViewSetMixin

from app01.app_auth import MyAuthentication
# ViewSetMixin一定放在前面,重写as_view方法
class Books6View(ViewSetMixin,GenericAPIView):
    authentication_classes = [MyAuthentication]
    def get_all_book(self,request):
        books = Book.objects.all()
        book_ser = BookSerializer(books, many=True)
        return Response(book_ser.data)

全局认证

settings.py

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.app_auth.MyAuthentication",]
}

登录视图类需要排除认证,在类里写空列表

authentication_classes = []

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值