源码分析:三大认证组件的封装
组件的认证配置:
模型层: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