python-etcd3 连接 etcd3

创建日期: 2025-02-13 12:29 | 作者: 风波 | 浏览次数: 21 | 分类: KV数据库

文档地址:https://python-etcd3.readthedocs.io/en/latest/

1. 安装

1.1 Stable release

pip install etcd3 -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

注意⚠️:如果使用这种方式安装,可能需要降级 protobuf (参考: https://stackoverflow.com/questions/72899948/how-to-downgrade-protobuf)

pip install protobuf==3.20.*

1.2 From sources

获取代码 git clone https://github.com/kragniz/python-etcd3

或者

curl -OL https://github.com/kragniz/python-etcd3/tarball/master

安装

pip install setuptools  -i https://mirrors.aliyun.com/pypi/simple/  --trusted-host mirrors.aliyun.com
python setup.py install

2. 基本用法

import etcd3

etcd = etcd3.client(host='172.17.0.1', port=10379)
f = etcd.get('foo')
print(f)
etcd.delete('foo')

etcd.put('bar', 'bar-value')
f = etcd.get('bar')
print(f)

etcd.delete('bar')
f = etcd.get('bar')
print(f)

官方例子:

import etcd3

etcd = etcd3.client()

etcd.get('foo')
etcd.put('bar', 'doot')
etcd.delete('bar')

# locks
lock = etcd.lock('thing')
# do something
lock.release()

with etcd.lock('doot-machine') as lock:
    # do something

# transactions
etcd.transaction(
    compare=[
        etcd.transactions.value('/doot/testing') == 'doot',
        etcd.transactions.version('/doot/testing') > 0,
    ],
    success=[
        etcd.transactions.put('/doot/testing', 'success'),
    ],
    failure=[
        etcd.transactions.put('/doot/testing', 'failure'),
    ]
)

# watch key
watch_count = 0
events_iterator, cancel = etcd.watch("/doot/watch")
for event in events_iterator:
    print(event)
    watch_count += 1
    if watch_count > 10:
        cancel()

# watch prefix
watch_count = 0
events_iterator, cancel = etcd.watch_prefix("/doot/watch/prefix/")
for event in events_iterator:
    print(event)
    watch_count += 1
    if watch_count > 10:
        cancel()

# recieve watch events via callback function
def watch_callback(event):
    print(event)

watch_id = etcd.add_watch_callback("/anotherkey", watch_callback)

# cancel watch
etcd.cancel_watch(watch_id)

3. API Usage

import etcd3

# etcd = etcd3.client()
# etcd = etcd3.client(host='etcd-host-01', port=2379)
etcd = etcd3.client(grpc_options={
                        'grpc.http2.true_binary': 1,
                        'grpc.http2.max_pings_without_data': 0,
                    }.items())

etcd.put('/key', 'dooot')

检查结果

ETCDCTL_API=3 etcdctl get /key

3.1 API

class etcd3.Etcd3Client

class etcd3.Etcd3Client(host='localhost', port=2379, ca_cert=None, cert_key=None, cert_cert=None, timeout=None, user=None, password=None, grpc_options=None)[source]
>>> import etcd3
>>> etcd = etcd3.client()
>>> etcd.put('/thing/key', 'hello world')

Parameters: key – key in etcd to set value (bytes) – value to set key to lease (either Lease, or int (ID of lease)) – Lease to associate with this key. prev_kv (bool) – return the previous key-value pair Returns:
a response containing a header and the prev_kv Return type:
rpc_pb2.PutResponse

If the timeout was specified and event didn’t arrived method will raise WatchTimedOut exception.

etcd.transaction(
    compare=[
        etcd.transactions.value('/doot/testing') == 'doot',
        etcd.transactions.version('/doot/testing') > 0,
    ],
    success=[
        etcd.transactions.put('/doot/testing', 'success'),
    ],
    failure=[
        etcd.transactions.put('/doot/testing', 'failure'),
    ]
)

Parameters: compare – A list of comparisons to make success – A list of operations to perform if all the comparisons are true failure – A list of operations to perform if any of the comparisons are false Returns:
A tuple of (operation status, responses)

class etcd3.Member

class etcd3.Member(id, name, peer_urls, client_urls, etcd_client=None)

A member of the etcd cluster. Variables:
id – ID of the member name – human-readable name of the member peer_urls – list of URLs the member exposes to the cluster for communication client_urls – list of URLs the member exposes to clients for communication

Parameters: peer_urls – new list of peer urls the member will use to communicate with the cluster

Returns: Alarms

class etcd3.Lease

class etcd3.Lease(lease_id, ttl, etcd_client=None)[source]

A lease.

Variables:
id – ID of the lease ttl – time to live for this lease

class etcd3.Lock

class etcd3.Lock(name, ttl=60, etcd_client=None)[source]

A distributed lock.

This can be used as a context manager, with the lock being acquired and released as you would expect:

etcd = etcd3.client()

# create a lock that expires after 20 seconds
with etcd.lock('toot', ttl=20) as lock:
    # do something that requires the lock
    print(lock.is_acquired())

    # refresh the timeout on the lease
    lock.refresh()

Parameters: name (string or bytes) – name of the lock ttl (int) – length of time for the lock to live for in seconds. The lock will be released after this time elapses, unless refreshed - acquire(timeout=10)[source] Acquire the lock.

Params timeout: Maximum time to wait before returning. None means forever, any other value equal or greater than 0 is the number of seconds. Returns: True if the lock has been acquired, False otherwise. - release()[source] Release the lock.

21 浏览
17 爬虫
0 评论