Python的类型描述组件:Schematics
jopen
10年前
Python 库基础上的类型描述组件, 能对数据类型进行对比/合成为新结构,并进行验证和转换!
一些常见的用例:
- Design and document specific data structures
- Convert structures to and from different formats such as JSON or MsgPack
- Validate API inputs
- Remove fields based on access rights of some data's recipient
- Define message formats for communications protocols, like an RPC
- Custom persistence layers
示例
This is a simple Model.
>>> from schematics.models import Model >>> from schematics.types import StringType, URLType >>> class Person(Model): ... name = StringType(required=True) ... website = URLType() ... >>> person = Person({'name': u'Joe Strummer', ... 'website': 'http://soundcloud.com/joestrummer'}) >>> person.name u'Joe Strummer'
Serializing the data to JSON.
>>> import json >>> json.dumps(person.to_primitive()) {"name": "Joe Strummer", "website": "http://soundcloud.com/joestrummer"}
Let's try validating without a name value, since it's required.
>>> person = Person() >>> person.website = 'http://www.amontobin.com/' >>> person.validate() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "schematics/models.py", line 231, in validate raise ModelValidationError(e.messages) schematics.exceptions.ModelValidationError: {'name': [u'This field is required.']}
Add the field and validation passes
>>> person = Person() >>> person.name = 'Amon Tobin' >>> person.website = 'http://www.amontobin.com/' >>> person.validate() >>>