跳转到主要内容

未提供项目描述

项目描述

django-dataclass-autoserialize

对oxan的django-dataclass-serialize(临时托管在此)的微小修改扩展。使其与drf-yasg的使用更加愉快。

此软件包的目标是将APIView代码尽可能简洁。它试图解决的主要痛点是

  1. 必须单独定义参数类和序列化。
  2. 与drf-yasg很好地集成,无需重复信息。

安装

pip install django-dataclass-autoserialize

文档

简单用法

这是一个典型用法的示例。直接从示例项目中拉取。

from __future__ import annotations
from django_dataclass_autoserialize import AutoSerialize, swagger_post_schema, swagger_get_schema
from dataclasses import dataclass

from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView


@dataclass
class InputParam(AutoSerialize):
    a: int
    b: int

    @classmethod
    def example(cls) -> InputParam:
        # this is actually optional but it will show up
        # in swagger doc
        return cls(a=3, b=2)


@dataclass
class ComputeResponse(AutoSerialize):
    msg: str
    result: int

    @classmethod
    def example(cls) -> ComputeResponse:
        return cls(msg='hello world', result=5)


class AddView(APIView):

    @swagger_post_schema(
        body_type=InputParam,
        response_types={200: ComputeResponse}
    )
    def post(self, request: Request) -> Response:
        param = InputParam.from_post_request(request)
        return ComputeResponse(msg='add successfully',
                               result=param.a + param.b).to_response()


class SubtractView(APIView):
    @swagger_get_schema(
        query_type=InputParam,
        response_types={200: ComputeResponse}
    )
    def get(self, request: Request) -> Response:
        param = InputParam.from_get_request(request)
        return ComputeResponse(msg='subtract successfully',
                               result=param.a - param.b).to_response()

Swagger将显示如下swagger示例1 swagger示例2

自定义

在底层,它使用djangorestframework-dataclasses。因此,可以对dataclass进行的所有自定义也在此处应用。例如,您可以添加如下serializer_kwargs

@dataclasses.dataclass
class Person:
    email: str = dataclasses.field(metadata={'serializer_field': fields.EmailField()})
    age: int = dataclasses.field(metadata={'serializer_kwargs': {'min_value': 0}})

验证

可以通过重写validate_data(cls, obj)方法来执行对象的验证。例如

class Numbers(AutoSerialize):
    a: int
    b: int

    @classmethod
    def validate_data(cls, obj: Numbers) -> Numbers:
        from rest_framework.exceptions import ValidationError
        if obj.a + obj.b > 1000:
            raise ValidationError('too big')
        return obj

Swagger

drg-yasg的集成通过swagger_get_schemaswagger_get_schema装饰器完成。请参阅使用示例。除了query_type/body_typeresponse_types之外的键词都转发到drf-yasg的swagger_auto_schema

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分布

本发布没有可用的源分布文件。请参阅生成分发存档的教程。

构建分布

django_dataclass_autoserialize-1.0.1-py3-none-any.whl (5.1 kB 查看哈希值)

上传时间 Python 3

由以下组织支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面