从数据类生成json模式

dataclasses-jsonschema的Python项目详细描述


https://travis-ci.org/s-knibbs/dataclasses-jsonschema.svg?branch=masterhttps://badge.fury.io/py/dataclasses-jsonschema.svgLanguage grade: Python

从Python3.7数据类生成JSON模式的库。python 3.6通过dataclasses backport支持。旨在成为类似项目(如marshmallow&;pydantic)的更轻量级替代方案。

功能概述

  • 支持draft-04、draft-06、swagger 2.0和openapi 3模式类型
  • 序列化和反序列化
  • 根据生成的模式进行数据验证
  • APISpec支持。示例below

安装

~$ pip install dataclasses-jsonschema

要使用fastjsonschema提高验证性能,请使用以下命令安装:

~$ pip install dataclasses-jsonschema[fast-validation]

示例

fromdataclassesimportdataclassfromdataclasses_jsonschemaimportJsonSchemaMixin@dataclassclassPoint(JsonSchemaMixin):"A 2D point"x:floaty:float

生成架构:

>>>pprint(Point.json_schema()){'description':'A 2D point','type':'object','properties':{'x':{'format':'float','type':'number'},'y':{'format':'float','type':'number'}},'required':['x','y']}

串行数据:

>>>Point(x=3.5,y=10.1).to_dict(){'x':3.5,'y':10.1}

反序列化数据:

>>>Point.from_dict({'x':3.14,'y':1.5})Point(x=3.14,y=1.5)>>>Point.from_dict({'x':3.14,y:'wrong'})dataclasses_jsonschema.ValidationError:'wrong'isnotoftype'number'

生成用于嵌入到API规范中的架构:

fromdataclasses_jsonschemaimportJsonSchemaMixin,SchemaType@dataclassclassAddress(JsonSchemaMixin):"""Postal Address"""building:strstreet:strcity:str@dataclassclassCompany(JsonSchemaMixin):"""Company Details"""name:straddress:Address>>>pprint(JsonSchemaMixin.all_json_schemas(schema_type=SchemaType.SWAGGER_V3)){'Address':{'description':'Postal Address','properties':{'building':{'type':'string'},'city':{'type':'string'},'street':{'type':'string'}},'required':['building','street','city'],'type':'object'},'Company':{'description':'Company Details','properties':{'address':{'$ref':'#/components/schemas/Address'},'name':{'type':'string'}},'required':['name','address'],'type':'object'}}

可以使用NewType

添加自定义验证规则
fromdataclasses_jsonschemaimportJsonSchemaMixin,FieldEncoderPhoneNumber=NewType('PhoneNumber',str)classPhoneNumberField(FieldEncoder):@propertydefjson_schema(self):return{'type':'string','pattern':r'^(\([0-9]{3}\))?[0-9]{3}-[0-9]{4}$'}JsonSchemaMixin.register_field_encoders({PhoneNumber:PhoneNumberField()})@dataclassclassPerson(JsonSchemaMixin):name:strphone_number:PhoneNumber

更多示例see the tests

apispec插件

v2.5.0中的新功能

openapi&swagger规范可以使用apispec插件生成:

fromtypingimportOptional,ListfromdataclassesimportdataclassfromapispecimportAPISpecfromapispec_webframeworks.flaskimportFlaskPluginfromflaskimportFlask,jsonifyimportpytestfromdataclasses_jsonschema.apispecimportDataclassesPluginfromdataclasses_jsonschemaimportJsonSchemaMixin# Create an APISpecspec=APISpec(title="Swagger Petstore",version="1.0.0",openapi_version="3.0.2",plugins=[FlaskPlugin(),DataclassesPlugin()],)@dataclassclassCategory(JsonSchemaMixin):"""Pet category"""name:strid:Optional[int]@dataclassclassPet(JsonSchemaMixin):"""A pet"""categories:List[Category]name:strapp=Flask(__name__)@app.route("/random")defrandom_pet():"""A cute furry animal endpoint.
    ---
    get:
      description: Get a random pet
      responses:
        200:
          content:
            application/json:
              schema: Pet
    """pet=get_random_pet()returnjsonify(pet.to_dict())# Dependant schemas (e.g. 'Category') are added automaticallyspec.components.schema("Pet",schema=Pet)withapp.test_request_context():spec.path(view=random_pet)

待办事项

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java InputStream对象在声明后关闭   java未定义名为“transactionManager”的bean重命名transactionManager   java“jar”命令何时会拒绝将类添加到java中。jar文件?   java JPA标准依赖WHERE子句   安卓中从SD卡读取文本文件时出现java错误   java直接启用类似位置的权限   使用@WebMvcTest和Mockito-BDDMockito对SpringBoot-RestController进行java测试   java JSESSIONID存储在哪里?   java jtextarea鼠标事件覆盖容器鼠标事件   java DRL无法解析动态加载的类   java是从一个方法返回多个对象的最简单方法   java自定义按钮/编辑框是否不可见?   java GUI如何在保存用户输入的同时在面板或框架之间切换   swing Java自定义JSlider不会更新   GridBagLayout中的java超过1个JPanel   java从ProjectReactor中的flux中采样除第一个元素外的所有元素   Java泛型和泛型类型   Java代码生成宽指令的jvm