KTO客户机
kinto-client的Python项目详细描述
kinto是一种允许存储和同步任意数据的服务, 附加到用户帐户。它的主要接口是http。
kinto client是一个python库,它简化了与 一个kinto服务器实例。A project with related goals is also available for JavaScript。
安装
使用pip:
$ pip install kinto-client
用法
注意
操作总是直接在服务器上执行,而不是 同步功能尚未实现。
- 此api的第一个版本不缓存任何访问,也不提供任何 刷新机制。如果你想确定你有最新的可用数据, 再打一个电话。
以下是api提供的内容的概述:
fromkinto_clientimportClientclient=Client(server_url="http://localhost:8888/v1",auth=('alexis','p4ssw0rd'))records=client.get_records(bucket='default',collection='todos')fori,recordinenumerate(records['data']):record['title']='Todo #%d'%iforrecordinrecords:client.update_record(record)
创建客户机
传递的auth参数是一个requests 身份验证策略,允许使用任何适合您的方案进行身份验证 最好的。
默认情况下,kinto支持 Firefox Accounts和 基本身份验证策略。
fromkinto_clientimportClientcredentials=('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。
fromkinto_clientimportClientcredentials=('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')
记录
可以从集合中检索记录并将其保存到集合中。
记录是带有“权限”和“数据”键的dict。
# You can pass a python dictionary to create the record# bucket='default' can be omitted since it's the default valueclient.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')
权限
By default, authors will get read and write access to the manipulated objects. It is possible to change this behavior by passing a dict to the permissions parameter.
client.create_record(data={'foo':'bar'},permissions={'read':['group:groupid']},collection='todos')
注意
对一个遥远的物体的每一个创建或修改操作都可以给出 a权限参数。
存储桶、集合和记录具有可编辑的权限。 例如,要授予对特定记录的“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)执行批处理请求:
withclient.batch()asbatch:foridxinrange(0,100):batch.update_record(data={'id':idx})
批处理对象与另一个客户端共享相同的方法。
错误时重试
当服务器被限制(在高负载或维护下)时,它可以 返回错误响应。
因此,客户端可以重试发送相同的请求,直到成功为止。 要启用此功能,请指定客户端上的重试次数:
client=Client(server_url='http://localhost:8888/v1',auth=credentials,retry=10)
kinto协议允许服务器define the duration in seconds between retries。 可以(但不建议)在客户端中强制使用此值:
client=Client(server_url='http://localhost:8888/v1',auth=credentials,retry=10,retry_after=5)
生成素g终点路径
您可能希望生成一些终结点路径,可以使用 获取终结点实用程序以执行此操作:
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'
命令行脚本
为了获得脚本的公共参数和选项,提供了一些实用程序 从命令行参数简化客户端的配置和初始化。
importargparseimportloggingfromkinto_clientimportcli_utilslogger=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