• Django-rest framework框架的三大认证组件


    源码分析:三大认证组件的封装

    组件的认证配置:

    模型层:models.py

    class User(BaseModel):
        username = models.CharField(verbose_name='用户名', max_length=32)
        password = models.CharField(verbose_name='密码', max_length=64)
    
    
    class Car(BaseModel):
        name = models.CharField(verbose_name='汽车品牌', max_length=32)
        price = models.DecimalField(verbose_name='价格', max_digits=11, decimal_places=2, default=1.00)

     序列化层:serializer.py

    from rest_framework import serializers
    from . import models
    class UsersModelSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.User
            fields = ('username', 'password')
            extra_kwargs = {}
    
    class CarsModelSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.Car
            fields = ('name', 'price')
            extra_kwargs = {}

    路由层:urls,.py

    from django.conf.urls import url, include
    from . import views
    urlpatterns = [
        url(r'^users/(?P<pk>d+)/', views.UsersRetrieveAPIView.as_view()),
    
        url(r'^cars/$', views.CarsGenericViewSet.as_view({'get': 'list'})),
        url(r'^cars/(?P<pk>d+)/', views.CarsGenericViewSet.as_view({'get': 'retrieve'})),
    ]

    视图层:views.py

    from rest_framework import generics, viewsets, mixins
    from . import models, serializers
    
    
    # 局部禁用:视图类中 authentication_classes 字段可以完成局部控制
    class UsersRetrieveAPIView(generics.RetrieveAPIView):
        # 局部解除认证
        authentication_classes = ()
        queryset = models.User.objects.filter(is_delete=False)
        serializer_class = serializers.UsersModelSerializer
    
    from . import authentication
    class CarsGenericViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
        # 局部完成禁用
        authentication_classes = (authentication.TokenAuthentication, )
        queryset = models.Car.objects.filter(is_delete=False)
        serializer_class = serializers.CarsModelSerializer
  • 相关阅读:
    转:python时间日期处理小结
    vi 的一些常用操作-君子善假于物也
    没有了老师,该如何学习?
    git常用命令
    python 读配置文件
    Python中unittest用法实例
    python 单元测试unnitest-摘录自http://www.cnblogs.com/hackerain/p/3682019.html#undefined
    纯CSS实现立方体旋转
    CSS 3动画
    CSS 2D转换
  • 原文地址:https://www.cnblogs.com/Gaimo/p/11704625.html
Copyright © 2020-2023  润新知