Kinto客户端
项目描述
Kinto是一种允许存储和同步任意数据的服务,这些数据附属于用户账户。它的主要接口是HTTP。
kinto-client是一个Python库,它简化了与Kinto服务器实例的交互。还有一个与JavaScript相关的项目也可用。
安装
使用pip
$ pip install kinto-client
用法
此API的第一个版本不缓存任何访问,也不提供任何刷新机制。如果您想确保有最新的数据可用,请发出另一个调用。
以下是API提供内容的概述
from kinto_client import Client
client = Client(server_url="http://localhost:8888/v1",
auth=('alexis', 'p4ssw0rd'))
records = client.get_records(bucket='default', collection='todos')
for i, record in enumerate(records['data']):
record['title'] = 'Todo #%d' %i
for record in records:
client.update_record(record)
创建客户端
传递的auth参数是一个requests认证策略,允许使用最适合您的方案进行认证。
默认情况下,Kinto支持Firefox Accounts和基本认证策略。
from kinto_client import Client
credentials = ('alexis', 'p4ssw0rd')
client = Client(server_url='http://localhost:8888/v1',
auth=credentials)
在创建客户端时也可以传递bucket和collection,以便默认使用此值。
client = Client(bucket="payments", collection="receipts", auth=auth)
获取服务器信息
您可以使用server_info方法获取服务器信息
.. code-block:: python
from kinto_client import Client
client = Client(server_url='http://localhost:8888/v1') info = client.server_info() assert ‘schema’ in info[‘capabilities’], “Server doesn’t support schema validation.”
处理bucket
所有操作都基于bucket。一个应用程序同时处理多个bucket几乎没有意义(但这是可能的)。如果没有提供特定的bucket名称,则使用“default”bucket。
from kinto_client import Client
credentials = ('alexis', 'p4ssw0rd')
client = Client(server_url='http://localhost:8888/v1',
auth=credentials)
client.create_bucket('payments')
client.get_bucket('payments')
# It is also possible to manipulate bucket permissions (see later)
client.update_bucket('payments', permissions={})
# Or delete a bucket and everything under.
client.delete_bucket('payment')
# Or even every writable buckets.
client.delete_buckets()
集合
集合是存储记录的地方。
client.create_collection('receipts', bucket='payments')
# Or get an existing one.
client.get_collection('receipts', bucket='payments')
# To delete an existing collection.
client.delete_collection('receipts', bucket='payments')
# Or every collections in a bucket.
client.delete_collections(bucket='payments')
记录
可以从集合中检索记录并将其保存到集合中。
记录是一个包含“permissions”和“data”键的字典。
# You can pass a python dictionary to create the record
# bucket='default' can be omitted since it's the default value
client.create_record(data={'id': 1234, status: 'done', title: 'Todo #1'},
collection='todos', bucket='default')
# Retrieve all records.
record = client.get_records(collection='todos', bucket='default')
# Retrieve a specific record and update it.
record = client.get_record('89881454-e4e9-4ef0-99a9-404d95900352',
collection='todos', bucket='default')
client.update_record(record, collection='todos', bucket='default')
# Update multiple records at once.
client.update_records(records, collection='todos')
# It is also possible to delete a record.
client.delete_record(id='89881454-e4e9-4ef0-99a9-404d95900352',
collection='todos')
# Or every records of a collection.
client.delete_records(collection='todos')
权限
默认情况下,作者将获得对所操作对象的读取和写入访问权限。可以通过传递字典到permissions参数来更改此行为。
client.create_record( data={'foo': 'bar'}, permissions={'read': ['group:groupid']}, collection='todos')
bucket、collection和record都有可以编辑的权限。例如,为了给“leplatrem”访问特定的记录,您会这样做
record = client.get_record(1234, collection='todos', bucket='alexis')
record['permissions']['write'].append('leplatrem')
client.update_record(record)
# During creation, it is possible to pass the permissions dict.
client.create_record(data={'foo': 'bar'}, permissions={})
获取或创建
在某些情况下,您可能只想在bucket、collection或record不存在时创建它们。为此,您可以将if_not_exists=True传递给create_*方法
client.create_bucket('bucket', if_not_exists=True)
覆盖现有对象
大多数方法都有一个safe参数,默认为True。如果设置为True并且传递的data中存在if_match字段,则在请求中添加一个检查以确保记录在此期间没有被服务器端修改。
批量操作
与其为每个操作发出请求,不如批量请求。客户端将发出尽可能少的请求。
目前,批量操作仅支持写操作,因此无法在批处理中检索信息。
可以使用Python上下文管理器(with)执行批量请求
with client.batch() as batch:
for idx in range(0,100):
batch.update_record(data={'id': idx})
一批对象与另一个客户端共享相同的方法。
错误时重试
当服务器被限流(在高负载或维护中)时,它可能会返回错误响应。
因此,客户端可以重试发送相同的请求,直到成功。为此,请在客户端指定重试次数
client = Client(server_url='http://localhost:8888/v1',
auth=credentials,
retry=10)
Kinto 协议允许服务器 定义重试之间的秒数。在客户端中强制设置此值(虽然不推荐)是可能的
client = Client(server_url='http://localhost:8888/v1',
auth=credentials,
retry=10,
retry_after=5)
生成端点路径
您可能想要生成一些端点路径,可以使用 get_endpoint 工具来完成
client = Client(server_url='http://localhost:8888/v1',
auth=('token', 'your-token'),
bucket="payments",
collection="receipts")
print(client.get_endpoint("record",
id="c6894b2c-1856-11e6-9415-3c970ede22b0"))
# '/buckets/payments/collections/receipts/records/c6894b2c-1856-11e6-9415-3c970ede22b0'
命令行脚本
为了使脚本具有共同的参数和选项,提供了一些实用程序来简化客户端的配置和初始化
import argparse
import logging
from kinto_client import cli_utils
logger = logging.getLogger(__name__)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Download records")
cli_utils.set_parser_server_options(parser)
args = parser.parse_args()
cli_utils.setup_logger(logger, args)
logger.debug("Instantiate Kinto client.")
client = cli_utils.create_client_from_args(args)
logger.info("Fetch records.")
records = client.get_records()
logger.warn("%s records." % len(records))
脚本现在接受基本选项
$ python example.py --help usage: example.py [-h] [-s SERVER] [-a AUTH] [-b BUCKET] [-c COLLECTION] [-v] [-q] [-D] Download records optional arguments: -h, --help show this help message and exit -s SERVER, --server SERVER The location of the remote server (with prefix) -a AUTH, --auth AUTH BasicAuth token:my-secret -b BUCKET, --bucket BUCKET Bucket name. -c COLLECTION, --collection COLLECTION Collection name. -v, --verbose Show all messages. -q, --quiet Show only critical errors. -D, --debug Show all messages, including debug messages.
运行测试
在一个终端中,运行 Kinto 服务器
$ make runkinto
在另一个终端中,对其运行测试
$ make tests
项目详情
下载文件
下载适合您平台的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。