restler为web提供了灵活且可配置的json和xml对象序列化
restler-serialization的Python项目详细描述
restler是一个用于web的对象序列化库。它支持 将对象转换为json或xml。目前,它的目标是 谷歌应用引擎与Python2.7。
安装
使用easy_install或pip从pypi安装restler;或者下载 打包并运行:
python setup.py install
(运行setup.py需要设置工具。)
要在google app engine上使用,您需要在 restler路径中某个目录。
运行测试
运行restler的测试:
pip install -r requirements.txt -t lib python -m unittest discover
运行测试需要python 2.7、google app engine sdk或google cloud sdk
用法
可以使用to_json或to_xml使用默认设置序列化db.model或ndb.model实例。
>>> jean = Person(first_name="Jeanne", last_name="d'Arc", ssn="N/A") >>> to_json(jean) '{"first_name": "Jeanne", "last_name": "d\'Arc", "ssn": "N/A"}'
要仅包含某些字段,请使用ModelStrategy。 使用ModelStrategy时,需要使用restler模型装饰器。
>>> @ae_db_serializer >>> class User(db.Model) >>> ...
现在设置ModelStrategy
>>> person_strategy = ModelStrategy(Person).include("first_name", "last_name") >>> to_json(jean, person_strategy) '{"first_name": "Jeanne", "last_name": "d'Arc"}'
或者,要排除指定字段:
>>> person_strategy = ModelStrategy(Person, include_all_fields=True).exclude("ssn") >>> to_json(jean, person_strategy) '{"first_name": "Jeanne", "last_name": "d'Arc"}'
有关自定义序列化的详细信息,请参阅文档。