用于ETCD3的异步客户端库
txaioetcd的Python项目详细描述
txaioetcd是由etcd支持的对象关系远程持久映射层。
它还为一般twisted etcd应用程序提供了一个低级异步api,绕过 库的对象关系层。
安装
该实现是纯python代码,与python 2和3都兼容 在pypy上运行完美。 在服务器端,需要etcd 3.1或更高版本。安装txaioetcd
pip install txaioetcd
注意
库当前需要twisted,尽管该api旨在允许以后添加异步支持(欢迎使用prs!)没有破损。 但是除了底层的网络库之外,只有很小的纯python依赖项。 ETCD 2不工作。etcd 3.0还不够——至少在grpc http网关上看密钥还不起作用。
开始
获取以下入门的完整示例源代码 here。
首先,txaioetcd使用高级远程持久映射api, 为要持久化的数据定义至少一个类, 例如aUser class:
classUser(object):defmarshal(self):""" Marshal the object into a generic host language object. """@staticmethoddefunmarshal(obj):""" Parse a generic host language object into a native object of this class. """
然后为要与键值存储一起使用的槽定义一个表:
fromtxaioetcdimportpmap# users table schema (a table with UUID keys and CBOR values holding User objects)tab_users=pmap.MapUuidCbor(1,marshal=lambdauser:user.marshal(),unmarshal=User.unmarshal)
上面将定义一个表槽(索引为1),其中包含键的uuid和序列化的cbor 值的用户类的对象。
注意
用户类不是按字面意思显示的,而是仅“封送”和“解封” 持久映射类型的参数指定用户类的对象接口 到持久映射库。应用程序开发人员需要提供 相应的应用程序类封送/解封接口。
持久映射的键和值的可用类型包括:
- 字符串(utf8),例如MapUuidString,MapStringString,MapStringUuid,…
- 二进制,例如MapUuidBinary,MapStringBinary,…
- oid(uint64),例如MapUuidOid,MapOidCbor,…
- uuid(uint128),例如MapUuidCbor,MapUuidUuid,…
- json,例如MapUuidJson,MapOidJson,MapStringJson,…
- cbor,例如MapOidCbor,MapUuidCbor,MapStringCbor,…
- pickle(python),例如MapStringPickle,…
- 扁平缓冲区,例如MapUuidFlatbuffers,…
例如,以下是另一个有效的插槽定义:
# users table schema (a table with OID keys and Python Pickle values holding User objects)tab_users=pmap.MapOidPickle(2,marshal=lambdauser:user.marshal(),unmarshal=User.parse)
上面将定义一个表槽(带索引2),其中包含键的oid,并序列化python pickle 值的用户类的对象。
连接
首先打开与ETCD的连接作为备份存储:
fromtxaioetcdimportClient,Databaseetcd=Client(reactor,url='http://localhost:2379')db=Database(etcd)
要检查数据库连接:
revision=awaitdb.status()print('connected to etcd: revision',revision)
存储和加载对象
现在从上面的类创建一个本地python对象并将其存储在表中,该表位于etcd中:
user=User()user.name='foobar'user.oid=uuid.uuid4()# create an async writable transaction to modify etcd dataasyncwithdb.begin(write=True)astxn:tab_users[txn,user.oid]=user# data is committed when transaction leaves scope .. hereprint('user stored: {}'.format(user))
从表中加载本地python对象,该对象从etcd远程加载:
# create an async read-only transaction when only accessing data in etcdasyncwithdb.begin()astxn:user=awaittab_users[txn,user.oid]print('user loaded: {}'.format(user))
组合起来
要将所有部分放在一起并运行代码,可以使用以下样板文件
importtxaiotxaio.use_twisted()fromtwisted.internet.taskimportreactfromtwisted.internet.deferimportensureDeferredfromtxaioetcdimportClient,Databaseasyncdefmain(reactor):etcd=Client(reactor,url='http://localhost:2379')db=Database()revision=awaitdb.status()print('connected to etcd: revision',revision)# INSERT YOUR CODE HEREdef_main():returnreact(lambdareactor:ensureDeferred(main(reactor)))if__name__=='__main__':txaio.start_logging(level='info')_main()
在上面的占位符中插入操作etcd的代码。