JSON超模式客户端
pluct的Python项目详细描述
允许超媒体导航和 资源验证。
基本用法
importpluct# Load a resourceitem=pluct.resource('http://myapi.com/api/item',timeout=2)# Works with connect timeout# Verifying if the resource is valid for the current schemaitem.is_valid()# Use the resource as a dictionaryfirst_title=item['subitems'][0]['title']# Accessing the item schemaitem.schema['properties']['title']# Loading a related resourcecategory=item.rel('category')# With additional parameterscategory=item.rel('category',timeout=(1,2))# You can choose from request parameters: http://docs.python-requests.org/en/latest/api/#requests.Session.request
身份验证/自定义http客户端
Pluct使用Session 对象从requests包作为http客户端。
可以使用具有相同接口的任何其他客户端。
下面是一个使用alf,即OAuth 2客户机的示例:
frompluctimportPluctfromalf.clientimportClientalf=Client(token_endpoint='http://myapi.com/token',client_id='client-id',client_secret='secret')# Create a pluct session using the clientpluct=Pluct(client=alf)item=pluct.resource('http://myapi.com/api/item')
此会话中对架构或资源的所有后续请求都将 使用同一个客户端。
参数和uri扩展
URI Templates在跟踪资源链接时受支持。
url扩展的上下文将是资源^{tt2}的合并$ 属性和传递给资源的^{tt4}的params参数$ 方法。
URL模板未使用的任何变量都将用于查询 请求的字符串。
最好用一个例子来解释。考虑以下资源和 架构片段:
{"type":"article"}
{"...":"...","links":[{"rel":"search","href":"/api/search/{type}"}]}
下一个示例将search链接中的href解析为 /api/search/article?q=foo并将加载包含文本的文章 “foo”:
importpluct# Load a resourceitem=pluct.resource('http://myapi.com/api/item')articles=item.rel('search',params={'q':'foo'})
搜索图库只是传递一个不同的type 在params参数中,如下所示:
galleries=item.rel('search',params={'type':'gallery','q':'foo'})
要发送自己的身体数据,可以将对象作为数据发送。接下来就是 您的方法(放置、发布、获取或删除)包含来自对象的所有数据:
galleries=item.rel('create',data=item)
架构加载
加载资源时,将创建一个惰性模式架构,并 只有在访问时才会加载数据。
Pluct在 Content-type标题:
Content-Type:application/json;profile="http://myapi.com/api/schema"
参考($ref)
JSON Pointers在模式上是 也支持。
指针由字典标识,字典中的$ref键指向 外部URL或本地指针。
考虑到/api/definitionsurl上的以下定义:
{"address":{"type":"object","properties":{"line1":{"type":"string"},"line2":{"type":"string"},"zipcode":{"type":"integer"},}}}
使用上述定义的/api/schema上的这个模式:
{"properties":{"shippingAddress":{"$ref":"http://myapi.com/api/definitions#/address"},"billingAddress":{"$ref":"http://myapi.com/api/definitions#/address"},}}
可以按如下方式访问billingAddress:
importpluctschema=pluct.schema('http://myapi.com/api/schema')schema['properties']['billingAddress']['zipcode']=={"type":"integer"}
贡献
在github上分叉存储库: https://github.com/globocom/pluct
创建一个virtualenv并安装依赖项:
make setup
测试位于pluct/tests目录中,使用以下命令运行测试套件:
make test