• drfday4——认证、路由


    作业

    1 继承ModelViewSet,获取所有的,只获取前10条

    2 登陆接口,查询图书接口,必须登录后才能查看,token信息放在头里(认证组件),全局使用,局部禁用(login禁用)

    3 使用simplerouter自动生成路由

    # 模型表:
    class Book(models.Model):
        name = models.CharField(max_length=32)
        price = models.DecimalField(max_digits=5,decimal_places=2)
        publish = models.CharField(max_length=32)
    
    
    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)
    
        
     
    
    
    # ser.py
    from rest_framework.serializers import ModelSerializer
    from app01.models import Book
    
    
    class BookSerializer(ModelSerializer):
        class Meta:
            model = Book
            fields = '__all__'
            
            
     
    
    
    # app_auth.py
    from rest_framework.authentication import BaseAuthentication
    from app01 import models
    from rest_framework.exceptions import AuthenticationFailed
    
    
    class MyAuthentication(BaseAuthentication):
        def authenticate(self, request):
            token = request.META.get('HTTP_TOKEN')
            if token:
                user_token = models.UserToken.objects.filter(token=token)
                if user_token:
                    return user_token.first().user, token
                else:
                    raise AuthenticationFailed('认证失败')
            else:
                raise AuthenticationFailed('请求头中必须携带token')
                
     
    
    
    # settings
    INSTALLED_APPS = [
        'rest_framework'
    ]
    
    staticREST_FRAMEWORK = {
        "DEFAULT_AUTHENTICATION_CLASSES": ["app01.app_auth.MyAuthentication", ]
    }
    
    
    
    
    
    
    # 路由:
    from django.conf.urls import url
    from rest_framework import routers
    from app01 import views
    
    router = routers.SimpleRouter()
    router.register('books', views.BookViewSet)
    urlpatterns = [
        url(r'^login/', views.Login.as_view()),
    ]
    
    urlpatterns += router.urls
    
    
    
    
    
    
    # 视图:
    from app01 import models
    import uuid
    from rest_framework.response import Response
    from rest_framework.viewsets import ModelViewSet
    from app01.ser import BookSerializer
    from rest_framework.decorators import action
    
    
    # Create your views here.
    
    
    class Login(APIView):
        authentication_classes = []
    
        def post(self, request):
            username = request.data.get('username')
            password = request.data.get('password')
            user = models.User.objects.filter(username=username, password=password)
            if user:
                token = uuid.uuid4()
                user = user.first()
                models.UserToken.objects.update_or_create(defaults={'token': token}, user=user)
                return Response({'status': 100, 'msg': '登陆成功','token':token})
            else:
                return Response({'status': 101, 'msg': '用户名和密码错误'})
    
    
    class BookViewSet(ModelViewSet):
        queryset = models.Book.objects.all()
        serializer_class = BookSerializer
        print(queryset)
    
        @action(methods=['GET','POST'], detail=True)
        def get_many(self, request, pk):
            book = self.get_queryset()[:int(pk)]
    
            ser = self.get_serializer(book, many=True)
            return Response(ser.data)
    

    1 没有登陆无法获取图书数据:

    image-20200710014704135

    2 登陆

    image-20200710014904757

    2 将token 字符串加到请求头中,通过校验,获取图书数据

    image-20200710015250427

    3 用get_many方法获取指定数量的数据信息:

    image-20200710015534609

    image-20200710015611539

  • 相关阅读:
    Markdown
    DNS解析流程
    maven 的各种命令
    ES6初体验——(1)let和const命令
    table相关的选择器 & children()与find()的区别 & 选择器eq(n)与nth-child(n)的差异
    Java MD5加密类
    POI操作Excel异常Cannot get a text value from a numeric cell
    MyEclipse+SSH开发环境配置
    JdbcTemplate详解
    Spring配置声明
  • 原文地址:https://www.cnblogs.com/cainiaoqianxun/p/13277245.html
Copyright © 2020-2023  润新知