从数据类生成json模式
dataclasses-jsonschema的Python项目详细描述
从Python3.7数据类生成JSON模式的库。python 3.6通过dataclasses backport支持。旨在成为类似项目(如marshmallow&;pydantic)的更轻量级替代方案。
安装
~$ 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)
待办事项
- 根据pydantic和marshmallow等备选方案添加基准