1.1 DRF视图
- Django REST framework是一个建立在Django基础之上的Web 应用开发框架,可以快速的开发REST API接口应用。
- 它提供了序列化器Serialzier & ModelSerializer 的定义,可以帮助我们简化序列化与反序列化的过程,
- 提供丰富的类视图、扩展类、视图集来简化视图的编写工作。
- 还提供了认证、权限、频率、过滤、分页、接口文档等功能。
- REST framework提供了一个API 的Web可视化界面, 方便查看、测试接口。
特点
- 提供了定义序列化器的方法,可以快速将 模型类对象转为字典,便于序列化;
- 提供了丰富的类视图、Mixin扩展类,简化视图的编写;
- 丰富的定制层级:函数视图、类视图、视图集合到自动生成 API,满足各种需要;
- 多种身份认证和权限认证方式的支持;[jwt]
- 内置了限流系统;
- 直观的 API web 界面;【方便我们调试开发api接口】
- 可扩展性,插件丰富
1.1.1 模型创建
class Department(BaseModel):
"""
部门
"""
name = models.CharField(max_length=30)
class Meta:
db_table = 'tb_department'
def __str__(self):
return self.name
class Duty(BaseModel):
"""
职务
"""
name = models.CharField(max_length=30, verbose_name='职务名称')
def __str__(self):
return self.name
class Meta:
db_table = 'tb_duty'
class Staff(models.Model):
"""
员工
"""
SEX_CHOICE = (
(1, '男'),
(2, '女')
)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
duty = models.ForeignKey(Duty, on_delete=models.CASCADE)
name = models.CharField(max_length=30, verbose_name='姓名')
sex = models.IntegerField(choices=SEX_CHOICE, default=1, verbose_name='性别')
phone = models.CharField(max_length=11, verbose_name='手机号')
email = models.EmailField(max_length=60, verbose_name='邮箱')
census_register = models.CharField(max_length=200, verbose_name='户籍')
def __str__(self):
return self.name
class Meta:
db_table = 'tb_staff'
序列化器使用
作用:
1.进行数据的校验-----反序列 2.将模型类的对象转换为字典—序列化 3.减少代码量,提高编码效率----序列化器
序列化定义:
将模型类对象转为字典,然后经过Response转为json字符串--------称为序列化
反序列化定义:
将网络中的json字符串经过Request对象,转为字典或者类字典,然后经过序列化器转为模型类的对象------称为反序列化
定义模型类的序列化器,需继承
rest_framework.serializers.Serializer —序列化器
rest_framework.serializers.ModelSerializer —模型类的序列化器
Serializer使用方式
反序列化插入数据时,必须重写create方法;反序列化更新数据时,必须重写update方法。
class DepartmentSerializer(serializers.Serializer):
id = serializers.IntegerField(label='ID', readonly=True)
name = serializers.CharField(label='部门名称', max_length=30)
class DutySerializer(serializers.Serializer):
id = serializers.IntegerField(label='ID', readonly=True)
name = serializers.CharField(label='职务名称', max_length=30)
class StaffSerializer(serializers.Serializer):
SEX_CHOICE = (
(1, '男'),
(2, '女')
)
department = serializers.PrimaryKeyRelatedField(read_only=True)
duty = serializers.PrimaryKeyRelatedField(read_only=True)
name = serializers.CharField(max_length=30, label='姓名')
sex = serializers.ChoiceField(SEX_CHOICE, default=1, label='性别')
phone = serializers.CharField(max_length=11, label='手机号')
email = serializers.EmailField(max_length=60, label='邮箱')
census_register = serializers.CharField(max_length=200, label='户籍')
常用字段类型:
字段 | 字段构造方式 |
---|
BooleanField | BooleanField() | NullBooleanField | NullBooleanField() | CharField | CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True) | EmailField | EmailField(max_length=None, min_length=None, allow_blank=False) | RegexField | RegexField(regex, max_length=None, min_length=None, allow_blank=False) | SlugField | SlugField(maxlength=50, min_length=None, allow_blank=False) 正则字段,验证正则模式 [a-zA-Z0-9-]+ | URLField | URLField(max_length=200, min_length=None, allow_blank=False) | UUIDField | UUIDField(format=‘hex_verbose’) format: 1) ‘hex_verbose’ 如"5ce0e9a5-5ffa-654b-cee0-1238041fb31a" 2) ‘hex’ 如 “5ce0e9a55ffa654bcee01238041fb31a” 3)‘int’ - 如: “123456789012312313134124512351145145114” 4)‘urn’ 如: “urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a” | IPAddressField | IPAddressField(protocol=‘both’, unpack_ipv4=False, **options) | IntegerField | IntegerField(max_value=None, min_value=None) | FloatField | FloatField(max_value=None, min_value=None) | DecimalField | DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits: 最多位数 decimal_palces: 小数点位置 | DateField | DateField(format=api_settings.DATE_FORMAT, input_formats=None) | TimeField | TimeField(format=api_settings.TIME_FORMAT, input_formats=None) | DurationField | DurationField() | ChoiceField | ChoiceField(choices) choices与Django的用法相同 | MultipleChoiceField | MultipleChoiceField(choices) | FileField | FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) | ImageField | ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) | ListField | ListField(child=, min_length=None, max_length=None) | DictField | DictField(child=) |
选项参数:
参数名称 | 作用 |
---|
max_length | 最大长度:在反序列化时进行输入最大长度校验 | min_lenght | 最小长度:在反序列化时进行输入最小长度校验 | allow_blank | 是否允许为空:在反序列化时允许传空白字符串,默认不允许 | trim_whitespace | 是否截断左右空白字符,默认True | max_value | 最大值:在反序列化时进行输入最大值校验 | min_value | 最小值:在反序列化时进行输入最小值校验 |
通用参数:
参数名称 | 作用 |
---|
read_only | 表明该字段仅用于序列化输出,默认False | write_only | 表明该字段仅用于反序列化输入,默认False | required | 表明该字段在反序列化时必须输入,默认True | default | 反序列化时使用的默认值,如果不指明,在传递时默认值为0 | allow_null | 表明该字段是否允许传入None,默认False | validators | 该字段使用的验证器 自己定义函数,实现更加复杂的数据校验 | error_messages | 包含错误编号与错误信息的字典 | label | 用于HTML展示API页面时,显示的字段名称 | help_text | 用于HTML展示API页面时,显示的字段帮助提示信息 |
重点说明:
read_only :在进行序列化输出时进行显示,但在反序列化验证时不做校验write_only :在反序列化时进行校验,但在序列化时不进行输出该字段
ModelSerializer与常规的Serializer相同,但提供了:
- 基于模型类自动生成一系列字段
- 基于模型类自动生成validators
- 默认实现create()和update()方法,不需重写
ModelSerializer使用
class DepartmentModelSerializer(serializers.ModelSerializer):
class Meta:
model = Department
fields = '__all__'
class DutyModelSerializer(serializers.ModelSerializer):
class Meta:
model = Duty
fields = ("name",)
class StaffModelSerializer(serializers.ModelSerializer):
department = serializers.PrimaryKeyRelatedField(label="部门", queryset=Department.objects.all(), many=True)
duty = serializers.PrimaryKeyRelatedField(label="职责", queryset=Duty.objects.all(), many=True)
class Meta:
model = Staff
fields = ("id", "name", "sex", "phone", "department", "duty")
read_only_fields = ("id",)
write_only_fields = ("email",)
数据请求和响应
查询 所有数据, 使用Serializer类序列化输出。
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Department
from .serializer import DepartmentSerializer
class DepartmentView(APIView):
"""
使用序列化器返回数据
"""
def get(self, request):
department_list = Department.objects.all()
dep_serializer = DepartmentSerializer(department_list, many=True)
return Response(dep_serializer.data)
序列化器默认只能序列化一条数据,序列化多条数据需要加上many=True
使用 Serializer类来反序列化添加,需要在DepartmentSerializer下重写create方法
class DepartmentSerializer(serializers.Serializer):
id = serializers.IntegerField(label='ID', read_only=True)
name = serializers.CharField(label='部门名称', max_length=30)
def create(self, validated_data):
return Department.objects.create(**validated_data)
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Department
from .serializer import DepartmentSerializer
class DepartmentView(APIView):
"""
使用序列化器 添加数据
"""
def post(self, request):
name = request.data.get('name')
department_obj = Department.objects.filter(name=name)
if department_obj:
return Response({'msg': '部门存在', 'code': 400})
dep_serializer = DepartmentSerializer(data=request.data)
if dep_serializer.is_valid():
dep_serializer.save()
return Response({'msg': '添加成功', 'code': 200})
else:
return Response({'error': dep_serializer.errors, 'code': 400})
使用Serializer进行数据 更新, 需要重写update方法
class DepartmentSerializer(serializers.Serializer):
id = serializers.IntegerField(label='ID', read_only=True)
name = serializers.CharField(label='部门名称', max_length=30)
def update(self, instance, validated_data):
instance.name = validated_data.get('name')
instance.save()
return instance
修改的视图
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Department
from .serializer import DepartmentSerializer
class DepartmentView(APIView):
"""
使用序列化器返回数据
"""
def put(self, request):
dep_id = request.data.get("dep_id")
name = request.data.get('name')
dep_obj = Department.objects.filter(id=dep_id).first()
if dep_obj:
dep_serializer = DepartmentSerializer(instance=dep_obj, data={'name': name}, partial=True)
dep_serializer.is_valid(raise_exception=True)
dep_serializer.save()
return Response({'msg': dep_serializer.data, 'code': 200})
else:
return Response({'msg': '修改的数据不存在', 'code': 400})
instance要修改的对象 data 要修改的数据 partial=True 默认修改全部,为True时,可以修改部分字段
序列化时,Serializer和ModelSeialiaer没有区别;
反序列化时,ModelSerializer由于自带create方法和update方法,所以不用重写这两个方法。
class DepartmentView(APIView):
"""
使用序列化器 添加数据
"""
def post(self, request):
name = request.data.get('name')
department_obj = Department.objects.filter(name=name)
if department_obj:
return Response({'msg': '部门存在', 'code': 400})
dep_serializer = DepartmentModelSerializer(data=request.data)
if dep_serializer.is_valid():
dep_serializer.save()
return Response({'msg': '添加成功', 'code': 200})
else:
return Response({'error': dep_serializer.errors, 'code': 400})
APIView是django rest framework框架中的基类,使用前需要安装djangorestframework。APIView继承了django中的View,具有View的特性,相比较View进行了封装,主要内容有:
1、传入到视图方法中的是REST framework的Request对象,而不是Django的HttpRequest对象;
2、视图方法可以返回REST framework的Response对象,并为响应数据设置符合前端要求的格式;
3、任何APIException异常都会被捕获到,并且处理成合适的响应信息;
4、在进行dispatch()分发前,会对请求进行身份认证、权限检查、流量控制。 支持定义的属性:
- authentication_classes 列表或元祖,身份认证类 authentication_classes = [MyAuthentication,]
- permissoin_classes 列表或元祖,权限检查类
- throttle_classes 列表或元祖,流量控制类
1.2 GenericAPIView的使用
1.2.1 GenericAPIView是什么
GenericAPIView继承自 APIVIew,增加了对于列表视图和详情视图可能用到的通用支持方法,可搭配一个或多个Mixin扩展类,来实现其他更加高级的功能。
from rest_framework.generics import GenericAPIView
这个类内置了如下一些属性,这些属性可以帮助我们进行序列化及反序列化的操作。
列表视图与详情视图通用属性:
- queryset 列表视图的查询集
- serializer_class 视图使用的序列化器
列表视图使用:
- pagination_class分页控制类
- filter_backends过滤控制后端,对字段过滤
详情页视图使用:
- lookup_field 查询单一数据对象时使用的条件字段,默认为’pk’
- lookup_url_kwarg 查询单一数据时URL中的关键字参数,默认与look_field相同
列表与详情视图通用方法
- get_queryset(self)
- 返回视图使用的查询集,是列表视图与详情视图获取数据的基础
- 默认返回queryset属性,支持重写
- get_serializer_class(self)
- 返回序列化器类,默认返回serializer_class,可以重写
- get_serializer(self, *args, **kwargs)
详情视图单独方法
- get_object(self)
- 返回详情视图所需的模型类数据对象,默认使用lookup_field参数来过滤queryset。
- 若详情访问的模型类对象不存在,会返回404,如果访问到多个重复,也会报错,默认使用get方法进行ORM查询
- Department.objects.get(id=pk)
- 该方法会默认使用 APIView 提供的check_object_permissions方法检查当前对象是否有权限被访问
获取全部部门数据
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from .models import Department
from .serializer import DepartmentModelSerializer
class DepartmentListView(GenericAPIView):
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
def get(self, request):
department_list = self.get_queryset()
dep_serializer = self.get_serializer(department_list, many=True)
return Response(dep_serializer.data)
获取单个数据对象
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from .models import Department
from .serializer import DepartmentModelSerializer
class DepDetailView(GenericAPIView):
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
lookup_field = 'pk'
def get(self, request, pk):
department = self.get_object()
dep_serializer = self.get_serializer(department)
return Response(dep_serializer.data)
反序列化 添加数据
class DepartmentListView(GenericAPIView):
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
def post(self, request):
name = request.data.get('name')
department_obj = Department.objects.filter(name=name)
if department_obj:
return Response({'msg': '部门存在', 'code': 400})
dep_serializer = self.get_serializer(data=request.data)
if dep_serializer.is_valid():
dep_serializer.save()
return Response({'msg': '添加成功', 'code': 200})
else:
return Response({'error': dep_serializer.errors, 'code': 400})
1.3 混入扩展类
DRF框架提供了5个Mixin扩展类,封装了通用的增、删、改、查(一个和多个)的代码基本流程:
扩展类 | 封装方法 | 说明 |
---|
ListModelMixin | list | 封装获取一组数据的基本代码流程 | CreateModelMixin | create | 封装新增一条数据的基本代码流程 | RetrieveModelMixin | retrieve | 封装获取指定数据的基本代码流程 | UpdateModelMixin | update | 封装更新指定数据的基本代码流程 | DestroyModelMixin | destroy | 封装删除指定数据的基本代码流程 |
ListModelMixin
列表视图扩展类,提供list(request, *args, **kwargs) 方法快速实现列表视图,返回200状态码。
该Mixin的list方法会对数据进行过滤和分页。
源码:
class ListModelMixin(object):
"""
List a queryset.
"""
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
示例:
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin
from .models import Department
from .serializer import DepartmentModelSerializer
class DepartmentListView(GenericAPIView, ListModelMixin):
"""
部门展示
"""
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
CreateModelMixin
创建视图扩展类,提供create(request, *args, **kwargs) 方法快速实现创建资源的视图,成功返回201状态码。
如果序列化器对前端发送的数据验证失败,返回400错误。
源码:
class CreateModelMixin(object):
"""
Create a model instance.
"""
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def perform_create(self, serializer):
serializer.save()
def get_success_headers(self, data):
try:
return {'Location': str(data[api_settings.URL_FIELD_NAME])}
except (TypeError, KeyError):
return {}
示例:
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin
from .models import Department
from .serializer import DepartmentModelSerializer
class DepartmentCreateView(GenericAPIView, CreateModelMixin):
"""
部门添加
"""
serializer_class = DepartmentModelSerializer
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
RetrieveModelMixin
详情视图扩展类,提供retrieve(request, *args, **kwargs) 方法,可以快速实现返回一个存在的数据对象。
如果存在,返回200, 否则返回404。
源码:
class RetrieveModelMixin(object):
"""
Retrieve a model instance.
"""
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
return Response(serializer.data)
示例:
class DepartmentRetrieveView(GenericAPIView, RetrieveModelMixin):
"""
部门单个获取
"""
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
lookup_field = 'pk'
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
UpdateModelMixin
更新视图扩展类,提供update(request, *args, **kwargs) 方法,可以快速实现更新一个存在的数据对象。
成功返回200,序列化器校验数据失败时,返回400错误。
源码:
class UpdateModelMixin(object):
"""
Update a model instance.
"""
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
...
return Response(serializer.data)
def perform_update(self, serializer):
serializer.save()
示例:
class DepartmentUpdateView(GenericAPIView, UpdateModelMixin):
"""
部门修改
"""
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
lookup_field = 'pk'
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
DestroyModelMixin
删除视图扩展类,提供destroy(request, *args, **kwargs) 方法,可以快速实现删除一个存在的数据对象。
成功返回204,不存在返回404。
源码:
class DestroyModelMixin(object):
"""
Destroy a model instance.
"""
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
self.perform_destroy(instance)
return Response(status=status.HTTP_204_NO_CONTENT)
def perform_destroy(self, instance):
instance.delete()
示例:
class DepartmentRetrieveView(GenericAPIView, DestroyModelMixin):
"""
部门删除
"""
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
lookup_field = 'pk'
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
子类视图简介
Django框架为了方便视图的编写,还提供了9个子类视图类。
子类视图类 | 继承 | 请求处理方法 |
---|
ListAPIView | GenericAPIView、ListModelMixin | 提供 get 方法 | CreateAPIView | GenericAPIView、CreateModelMixin | 提供 post 方法 | RetrieveAPIView | GenericAPIView、RetrieveModelMixin | 提供 get 方法 | UpdateAPIView | GenericAPIView、UpdateModelMixin | 提供 put 方法 | DestroyAPIView | GenericAPIView、DestroyModelMixin | 提供 delete 方法 | ListCreateAPIView | GenericAPIView、ListModelMixin、CreateModelMixin | 提供 get 和 post 方法 | RetrieveUpdateAPIView | GenericAPIView、RetrieveModelMixin、UpdateModelMixin | 提供 get、put 方法 | RetrieveDestroyAPIView | GenericAPIView、RetrieveModelMixin、DestroyModelMixin | 提供 get 和 delete 方法 | RetrieveUpdateDestroyAPIView | GenericAPIView、RetrieveModelMixin、UpdateModelMixin、DestroyModelMixin | 提供 get、put、delete方法 |
注:子类视图都在from rest_framework.generics 模块中。
ListAPIView
提供get方法,可以获取多条数据
from rest_framework.generics import ListAPIView
from .models import Department
from .serializer import DepartmentModelSerializer
class DepListView(ListAPIView):
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
CreateAPIView
提供post方法,可以创建一条数据
from rest_framework.generics import CreateAPIView
from .serializer import DepartmentModelSerializer
class DepCreateView(CreateAPIView):
serializer_class = DepartmentModelSerializer
RetireveAPIView
提供get方法,获取某个具体数据的详情
from rest_framework.generics import RetrieveAPIView
from .models import Department
from .serializer import DepartmentModelSerializer
class DepDetailView(RetrieveAPIView):
lookup_field = 'pk'
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
DestoryAPIView
提供 delete 方法,可以删除某条存在数据
from rest_framework.generics import DestroyAPIView
from .models import Department
from .serializer import DepartmentModelSerializer
class DepDestroyView(DestroyAPIView):
lookup_field = 'pk'
queryset = Department.objects.all()
UpdateAPIView
提供 put 和 patch 方法,可以更新或者局部更新某条数据
from rest_framework.generics import UpdateAPIView
from .models import Department
from .serializer import DepartmentModelSerializer
class DepUpdateView(UpdateAPIView):
lookup_field = 'pk'
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
ListCreateAPIView
提供 post 和 get 方法,可以创建一条数据,或获取列表数据
from rest_framework.generics import ListCreateAPIView
from .models import Department
from .serializer import DepartmentModelSerializer
class DepListCreateView(ListCreateAPIView):
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
RetrieveUpdateAPIView
提供 get、put、patch 方法,可以获取一条数据详情,也可以更新一条数据
from rest_framework.generics import RetrieveUpdateAPIView
from .models import Department
from .serializer import DepartmentModelSerializer
class DepRetrieveUpdateView(RetrieveUpdateAPIView):
lookup_field = 'pk'
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
RetrieveDestroyAPIView
提供 get 和 delete 方法,可以获取和删除一条已存在数据
from rest_framework.generics import RetrieveDestroyAPIView
from .models import Department
from .serializer import DepartmentModelSerializer
class DepRetrieveDestroyView(RetrieveDestroyAPIView):
lookup_field = 'pk'
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
RetrieveUpdateDestoryAPIView
提供 get、put、patch、delete 方法,啥也能干
from rest_framework.generics import RetrieveUpdateDestroyAPIView
from .models import Department
from .serializer import DepartmentModelSerializer
class DepartmentAll(RetrieveUpdateDestroyAPIView):
lookup_field = 'pk'
queryset = Department.objects.all()
serializer_class = DepartmentModelSerializer
|