hal-json解析器和生成器
dougrain的Python项目详细描述
Dougrain是一个Python库,可以帮助您使用 Hypertext Application Language (哈尔)。它使用python对象来表示json文档,因此您可以使用 它带有您喜欢的任何json库。
兼容性
json hal草稿3、4和5。Python2.7,3.2和3.3。
这个版本符合JSON Hypermedia API Language Internet Draft 5, 但它也可以使用来自 Draft 4和 Draft 3。 在构建文档时,可以显式地选择草稿版本, 但默认行为是文档自动检测哪个草稿 使用。
这个版本在Python2.7上测试,包括PyPy、Python3.2和 Python3.3。
安装
您可能需要在install命令中使用sudo,或者在 维图阿列诺夫。
安装当前版本的最简单方法是使用pip:
$ pip install dougrain
您可以用通常的方式安装源的本地副本:
$ cd dougrain $ pip install -r requirements.txt $ python setup.py install
示例
Document.from_object从adict加载hal数据:
>>> from dougrain import Document >>> doc = Document.from_object( ... { ... "_embedded": { ... "r:post": { ... "_links": { ... "self": { ... "href": "/1" ... }, ... "r:site": { ... "href": "/" ... } ... }, ... "name": "First child" ... } ... }, ... "welcome": "Hi there!", ... "_links": { ... "curies": [ ... { ... "href": "http://localhost/rels/{rel}", ... "name": "r", ... "templated": True ... } ... ], ... "self": { ... "href": "/" ... }, ... "r:post": { ... "href": "/1" ... }, ... "r:tags": { ... "href": "/tags" ... } ... } ... }, ... base_uri="http://localhost/")
Document实例提供了查询文档的 属性、链接和嵌入资源。
>>> doc.properties['welcome'] 'Hi there!' >>> doc.links['r:tags'].url() 'http://localhost/tags' >>> doc.embedded['r:post'].url() 'http://localhost/1'
可以使用curies或uri引用指定链接关系:
>>> doc.links['r:tags'].url() 'http://localhost/tags' >>> doc.links['/rels/tags'].url() 'http://localhost/tags'
Builder提供了一个轻量级api,用于从头构建hal资源。 许多Builder的方法可以被链接:
>>> from dougrain import Builder >>> new_post = (Builder("/2").set_property('name', "Second Child") ... .add_curie('admin', "/adminrels/{rel}") ... .add_link('admin:privacy', "/2/privacy")) >>> import json >>> print(json.dumps(new_post.as_object(), indent=2)) { "_links": { "curies": [ { "href": "/adminrels/{rel}", "name": "admin", "templated": true } ], "self": { "href": "/2" }, "admin:privacy": { "href": "/2/privacy" } }, "name": "Second Child" }
Builder和Document可以一起使用。例如, Document.embed将接受一个Builder实例:
>>> doc.embed('r:post', new_post) >>> [post.properties['name'] for post in doc.embedded['/rels/post']] ['First child', 'Second child']