Django实现接口自动化平台(八)测试报告reports序列化器及视图【持续更新中】

上一章:

Django实现接口自动化平台(七)数据库设计_做测试的喵酱的博客-CSDN博客

下一章:

官方文档:

Serializers - Django REST framework

一、测试报告reports序列化器及视图

1.1 序列化器

apps/reports/serializers.py

# -*- coding:utf-8 -*-
# @Author: 喵酱
# @time: 2023 - 06 -12
# @File: serializers.py
# desc:
from rest_framework import serializers

from .models import Reports


class ReportsModelSerilizer(serializers.ModelSerializer):

    class Meta:
        model = Reports
        exclude = ('update_time',)
        read_only_fields = ('name', 'count', 'result', 'success')
        extra_kwargs = {
            "create_time": {
                "read_only": True,
                "format": "%Y年%m月%d日 %H:%M:%S"
            },
            "name": {
                "read_only": True,
            },
            "html": {
                "write_only": True
            },
            "summary": {
                "write_only": True
            }

        }

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['result'] = '成功' if data.get('result') else '失败'
        return data

1.1.1 代码解释:

1、 exclude:

You can set the exclude attribute to a list of fields to be excluded from the serializer.

For example:

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        exclude = ['users']

2、read_only_fields =()设置字段属性为只读 

3、extra_kwargs = {} ,设置字段的属性。

4、自定义字段 to_representation

官方文档:Serializer fields - Django REST framework

Custom fields

If you want to create a custom field, you'll need to subclass Field and then override either one or both of the .to_representation() and .to_internal_value() methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.

The .to_representation() method is called to convert the initial datatype into a primitive, serializable datatype.

The .to_internal_value() method is called to restore a primitive datatype into its internal python representation. This method should raise a serializers.ValidationError if the data is invalid.

自定义字段
如果您想创建一个自定义字段,您需要子类化field,然后重写.to_representation()和.to_internal_value()方法中的一个或两个。这两个方法用于在初始数据类型和原始的、可序列化的数据类型之间进行转换。基本数据类型通常是数字、字符串、布尔值、日期/时间/datetime或None中的任何一种。它们也可以是任何类似列表或字典的对象,只包含其他基本对象。可能支持其他类型,这取决于您正在使用的呈现器。

调用.to_representation()方法将初始数据类型转换为可序列化的原始数据类型。

调用.to_internal_value()方法将原始数据类型恢复为其内部python表示。此方法应引发序列化器。如果数据无效,则返回ValidationError。

Examples

A Basic Custom Field

Let's look at an example of serializing a class that represents an RGB color value:

class Color:
    """
    A color represented in the RGB colorspace.
    """
    def __init__(self, red, green, blue):
        assert(red >= 0 and green >= 0 and blue >= 0)
        assert(red < 256 and green < 256 and blue < 256)
        self.red, self.green, self.blue = red, green, blue

class ColorField(serializers.Field):
    """
    Color objects are serialized into 'rgb(#, #, #)' notation.
    """
    def to_representation(self, value):
        return "rgb(%d, %d, %d)" % (value.red, value.green, value.blue)

    def to_internal_value(self, data):
        data = data.strip('rgb(').rstrip(')')
        red, green, blue = [int(col) for col in data.split(',')]
        return Color(red, green, blue)

1.2 视图

apps/reports/views.py

import logging
import json

from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework import permissions
from rest_framework import mixins
from django.http.response import StreamingHttpResponse
from rest_framework.response import Response
from rest_framework import status

from . import serializers
from .models import Reports
from utils.pagination import PageNumberPagination

logger = logging.getLogger('miaostudydjango')


class ReportViewSet(mixins.ListModelMixin,
                    mixins.RetrieveModelMixin,
                    mixins.DestroyModelMixin,
                    viewsets.GenericViewSet):
    queryset = Reports.objects.all()
    serializer_class = serializers.ReportsModelSerilizer
    permission_classes = [permissions.IsAuthenticated]


    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        try:
            summary = json.loads(instance.summary, encoding='utf-8')
            return Response({
                'id': instance.id,
                'summary': summary
            }, status=status.HTTP_200_OK)
        except Exception:
            return Response({
                'err': '测试报告summary格式有误'
            }, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True)
    def download(self, request, *args, **kwargs):
        # 1、获取html源码
        instance = self.get_object()

        # 2、将html源码转化为生成器对象
        # byte_data = instance.html.encode('utf-8')
        byte_data = instance.html

        # 3、StreamingHttpResponse对象
        response = StreamingHttpResponse(iter(byte_data))
        # StreamingHttpResponse、HttpResponse、Response,这些['key'] = 'value',可以添加响应头数据
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = f"attachment; filename*=UTF-8 '' {instance.name + '.html'}"

        return response

1.2.1 代码解释

1.3 路由

apps/reports/urls.py

from rest_framework import routers

from . import views


router = routers.SimpleRouter()
router.register(r'reports', views.ReportViewSet)

urlpatterns = [
]

urlpatterns += router.urls

miaostudydjango/urls.py

urlpatterns = [
    path('', include('reports.urls')),
    ]

猜你喜欢

转载自blog.csdn.net/qq_39208536/article/details/131168880