JSON Hyper Schema客户端
项目描述
A JSON Hyper Schema客户端,允许超媒体导航和资源验证。
基本用法
import pluct
# Load a resource
item = pluct.resource('http://myapi.com/api/item', timeout=2) # Works with connect timeout
# Verifying if the resource is valid for the current schema
item.is_valid()
# Use the resource as a dictionary
first_title = item['subitems'][0]['title']
# Accessing the item schema
item.schema['properties']['title']
# Loading a related resource
category = item.rel('category')
# With additional parameters
category = 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客户端的示例
from pluct import Pluct
from alf.client import Client
alf = Client(
token_endpoint='http://myapi.com/token',
client_id='client-id',
client_secret='secret')
# Create a pluct session using the client
pluct = Pluct(client=alf)
item = pluct.resource('http://myapi.com/api/item')
在此会话中,后续对模式或资源的所有请求都将使用相同的客户端。
参数和URI扩展
在跟踪资源链接时支持URI模板。
URL扩展的上下文将是资源data属性和传递给资源rel方法的params参数的合并。
任何未被URL模板消耗的变量将用于请求的查询字符串。
以下是一个示例。考虑以下资源和模式片段
{
"type": "article"
}
{
"...": "...",
"links": [
{
"rel": "search",
"href": "/api/search/{type}"
}
]
}
下一个示例将解析搜索链接中的href到/api/search/article?q=foo,并将加载包含文本“foo”的文章
import pluct
# Load a resource
item = pluct.resource('http://myapi.com/api/item')
articles = item.rel('search', params={'q': 'foo'})
要搜索图库,只需在params参数中传递不同的type即可,如下所示
galleries = item.rel('search', params={'type': 'gallery', 'q': 'foo'})
要发送自己的正文数据,可以发送对象作为数据。这将遵循你的方法(PUT、POST、GET或DELETE)并带上对象中的所有数据
galleries = item.rel('create', data=item)
模式加载
当加载资源时,将创建一个懒加载模式模式,其数据仅在访问时才加载。
Pluct在Content-type头部的profile参数中查找模式URL。
Content-Type: application/json; profile="http://myapi.com/api/schema"
参考($ref)
JSON指针在模式中也得到支持。
指针由一个包含指向外部URL或本地指针的$ref键的字典标识。
考虑以下在/api/definitions URL上的定义
{
"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
import pluct
schema = pluct.schema('http://myapi.com/api/schema')
schema['properties']['billingAddress']['zipcode'] == {"type": "integer"}
贡献
在Github上派生存储库: https://github.com/globocom/pluct
创建一个虚拟环境并安装依赖项
make setup
测试在pluct/tests目录中,使用以下命令运行测试套件
make test
项目详情
关闭
pluct-1.2.7.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 1d6a771b33ca5c5e830fc60abd3a526f6a1ee868a5afad784353d36c0a7abe33 |
|
MD5 | 123f9372eaf304a9637a6f16436fcda4 |
|
BLAKE2b-256 | 5d02dc38be684d767642e7c5da5d74f52fabce0100c0e81352eb160afb2175de |