从数据类生成JSON模式
dataclasses-jsonschema-rereleased的Python项目详细描述
从Python3.7数据类生成JSON模式的库。python3.6通过dataclasses backport得到支持。旨在成为类似项目(如marshmallow&;pydantic)的更轻量级替代方案。在
示例
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'
生成多个模式
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中的新功能
可以使用apispec插件生成OpenAPI和Swagger规范:
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: $ref: 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)
托多
- 添加针对可选方案的基准,如pydantic和marshmallow
- 项目
标签: