a tool to serialize objects by schema
Project description
schemaconvertor提供了一种使用schema来转换对象的方法,通过schema,可以指定该对象序列化的部分和对应的类型,其结果可以进一步序列化为json。
安装:pip install schemaconvertor
版本:0.3
演示
假设有个简单的数据类型User:
from collections import namedtuple
User = namedtuple("User", ["name", "password", "age"])
可以通过指定schema来转换对象:
schema = {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer"
}
}
}
user = User(name="lyc", password="schemaconvertor", age="24")
from schemaconvertor.convertor import convert_by_schema
print convert_by_schema(user, schema)
输出: > {‘age’: 24, ‘name’: ‘lyc’}
更多示例:demo 0.3
说明
基本字段
version
version字段标识着Schema版本。
description
description字段标识着Schema说明。
encoding
encoding指定Schema的string字段的字符编码,默认是utf-8。
decoderrors
decoderrors指定Schema的string字段解码失败的操作,用于str.decode的第二个参数,主要有strict,ignore,replace三种可选参数,默认是strict。
type
type字段指定对应待转换数据的最终类型,主要类型对应如下表:
type |
Python |
---|---|
string |
unicode |
object |
dict |
integer |
int |
float |
float |
number |
int/float |
boolean |
bool |
dict |
dict |
array |
list |
null |
NoneType |
raw |
object |
type字段直接影响转换行为,因此基本上每个Schema都需指定type,为简化表达,当一个Schema仅有type一项时,可以直接使用type的值简化表示为Schema。
typeOf
当前仅在声明typeOf字段时可以不指定type,typeOf指示如何根据数据的类型选择对应的Schema。可以使用真实的Python类型或类型元组作为key(作为isinstance的第二个参数)。
default
default字段仅用在typeOf字段内,用于指示缺省类型表示的Schema。
items
items字段仅在type为array时生效,用于描述序列中的每一项对应的Schema。
properties
items字段仅在type为dict或object时生效,指定给出的项的Schema(没有指定的项不会处理)。
patternProperties
items字段仅在type为dict或object时生效,指定符合给定的正则表达式的项的Schema(使用re.search匹配)。
附加信息
Schema使用lazy compile方式,仅在转换使用时自动编译,初始化代价极小。
子Schema中如无显式声明,version,description,encoding,decoderrors自动继承父Schema对应的值。
typeOf能够识别继承关系,但针对使用数据真实类型的情况有优化。
typeOf指定多种类型时不要使用list等非hashable类型。
对于object的情况是使用ObjAsDictAdapter将数据包装成类dict对象进行转换的。
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for schemaconvertor-0.3.1.0-py2.7.egg
Algorithm | Hash digest | |
---|---|---|
SHA256 | a26b712edcc83ba8b0de6eade3dea6fd5b1c1a60a7301801cb8984582a3602d6 |
|
MD5 | 3b016e9b833578f1cc420ddbc35e7d40 |
|
BLAKE2b-256 | 14802aa3f4cdc11e6e00119e103aa1c5ac9ef1ab34bfa49c4a82950c7dec5d2c |