Package: python-etcd
python-etcd documentationA python client for Etcdhttps://github.com/coreos/etcdOfficial documentation:http://python-etcd.readthedocs.org/InstallationPre-requirementsThis version of python-etcd will only work correctly with the etcd server version 2.0.x or later. If you are running an older version of etcd, please use python-etcd 0.3.3 or earlier.This client is known to work with python 2.7 and with python 3.3 or above. It is not tested or expected to work in more outdated versions of python.From source$pythonsetup.pyinstallUsageThe basic methods of the client have changed compared to previous versions, to reflect the new API structure; however a compatibility layer has been maintained so that you don’t necessarily need to rewrite all your existing code.Create a client objectimportetcdclient=etcd.Client()# this will create a client against etcd server running on localhost on port 4001client=etcd.Client(port=4002)client=etcd.Client(host='127.0.0.1',port=4003)client=etcd.Client(host=(('127.0.0.1',4001),('127.0.0.1',4002),('127.0.0.1',4003)))client=etcd.Client(host='127.0.0.1',port=4003,allow_redirect=False)# wont let you run sensitive commands on non-leader machines, default is true# If you have defined a SRV record for _etcd._tcp.example.com pointing to the clientsclient=etcd.Client(srv_domain='example.com',protocol="https")# create a client against https://api.example.com:443/etcdclient=etcd.Client(host='api.example.com',protocol='https',port=443,version_prefix='/etcd')Write a keyclient.write('/nodes/n1',1)# with ttlclient.write('/nodes/n2',2,ttl=4)# sets the ttl to 4 secondsclient.set('/nodes/n2',1)# Equivalent, for compatibility reasons.Read a keyclient.read('/nodes/n2').valueclient.read('/nodes',recursive=True)#get all the values of a directory, recursively.client.get('/nodes/n2').value# raises etcd.EtcdKeyNotFound when key not foundtry:client.read('/invalid/path')exceptetcd.EtcdKeyNotFound:# do somethingprint"error"Delete a keyclient.delete('/nodes/n1')Atomic Compare and Swapclient.write('/nodes/n2',2,prevValue=4)# will set /nodes/n2 's value to 2 only if its previous value was 4 andclient.write('/nodes/n2',2,prevExist=False)# will set /nodes/n2 's value to 2 only if the key did not exist beforeclient.write('/nodes/n2',2,prevIndex=30)# will set /nodes/n2 's value to 2 only if the key was last modified at index 30client.test_and_set('/nodes/n2',2,4)#equivalent to client.write('/nodes/n2', 2, prevValue = 4)You can also atomically update a result:result=client.read('/foo')print(result.value)# barresult.value+=u'bar'updated=client.update(result)# if any other client wrote '/foo' in the meantime this will failprint(updated.value)# barbarWatch a keyclient.read('/nodes/n1',wait=True)# will wait till the key is changed, and return once its changedclient.read('/nodes/n1',wait=True,timeout=30)# will wait till the key is changed, and return once its changed, or exit with an exception after 30 seconds.client.read('/nodes/n1',wait=True,waitIndex=10)# get all changes on this key starting from index 10client.watch('/nodes/n1')#equivalent to client.read('/nodes/n1', wait = True)client.watch('/nodes/n1',index=10)Refreshing key TTL(Since etcd 2.3.0) Keys in etcd can be refreshed without notifying current watchers.This can be achieved by setting the refresh to true when updating a TTL.You cannot update the value of a key when refreshing it.client.write('/nodes/n1','value',ttl=30)# sets the ttl to 30 secondsclient.refresh('/nodes/n1',ttl=600)# refresh ttl to 600 seconds, without notifying current watchersLocking module# Initialize the lock object:# NOTE: this does not acquire a lock yetclient=etcd.Client()# Or you can custom lock prefix, default is '/_locks/' if you are using HEADclient=etcd.Client(lock_prefix='/my_etcd_root/_locks')lock=etcd.Lock(client,'my_lock_name')# Use the lock object:lock.acquire(blocking=True,# will block until the lock is acquiredlock_ttl=None)# lock will live until we release itlock.is_acquired# Truelock.acquire(lock_ttl=60)# renew a locklock.release()# release an existing locklock.is_acquired# False# The lock object may also be used as a context manager:client=etcd.Client()withetcd.Lock(client,'customer1')asmy_lock:do_stuff()my_lock.is_acquired# Truemy_lock.acquire(lock_ttl=60)my_lock.is_acquired# FalseGet machines in the clusterclient.machinesGet leader of the clusterclient.leaderGenerate a sequential key in a directoryx=client.write("/dir/name","value",append=True)print("generated key: "+x.key)print("stored value: "+x.value)List contents of a directory#stick a couple values in the directoryclient.write("/dir/name","value1",append=True)client.write("/dir/name","value2",append=True)directory=client.get("/dir/name")# loop through directory childrenforresultindirectory.children:print(result.key+": "+result.value)# or just get the first child valueprint(directory.children.next().value)Development setupTo create a buildout,$pythonbootstrap.py$bin/buildoutto test you should have etcd available in your system path:$bin/testto generate documentation,$cddocs$makeRelease HOWTOTo make a releaseUpdate release date/version in NEWS.txt and setup.pyRun ‘python setup.py sdist’Test the generated source distribution in dist/Upload to PyPI: ‘python setup.py sdist register upload’News0.4.5Release date: 3-Mar-2017Remove dnspython2/3 requirementChange property name setter in lockFixed acl testsAdded version/cluster_version properties to clientFixes in lock when used as context managerFixed improper usage of urllib3 exceptionsMinor fixes for error classesIn lock return modifiedIndex to watch changesIn lock fix context manager exception handlingImprovments to the documentationRemove _base_uri only after refresh from clusterAvoid double update of _machines_cache0.4.4Release date: 10-Jan-2017Fix some testsUse sys,version_info tuple, instead of named tupleImprove & fix documentationFix python3 specific problem when blocking on contented lockAdd refresh key methodAdd custom lock prefix support0.4.3Release date: 14-Dec-2015Fix check for parameters in case of connection errorPython 3.5 compatibility and general python3 cleanupsAdded authentication and module for managing ACLsAdded srv record-based DNS discoveryFixed (again) logging of cluster id changesFixed leader lookupProperly retry request on exceptionClient: clean up open connections when deleting0.4.2Release date: 8-Oct-2015Fixed lock documentationFixed lock sequences due to etcd 2.2 changeBetter exception management during response processingFixed logging of cluster ID changesFixed subtree resultsDo not check cluster ID if etcd responses don’t contain the IDAdded a cause to EtcdConnectionFailed0.4.1Release date: 1-Aug-2015Added client-side leader electionAdded stats endpointsAdded loggingBetter exception handlingCheck for cluster ID on each requestAdded etcd.Client.members and fixed etcd.Client.leaderRemoved locking and election etcd supportAllow the use of etcd proxies with reconnectionsImplement pop: Remove key from etc and return the corresponding value.Eternal watcher can be now recursiveFix etcd.Client machinesDo not send parameters withNonevalue to etcdSupport ttl=0 in write.Moved pyOpenSSL into test requirements.Always set certificate information so redirects from http to https work.0.3.3Release date: 12-Apr-2015Forward leaves_only value in get_subtree() recursive callsFix README prevExists->prevExistAdded configurable version_prefixAdded support for recursive watchBetter error handling support (more detailed exceptions)Fixed some unreliable tests0.3.2Release date: 4-Aug-2014Fixed generated documentation version.0.3.1Release date: 4-Aug-2014Added consisten read optionFixed timeout parameter in read()Added atomic delete parameter supportFixed delete behaviourAdded update method that allows atomic updated on resultsFixed checks on write()Added leaves generator to EtcdResult and get_subtree for recursive fetchAdded etcd_index to EtcdResultChanged ethernal -> eternalUpdated urllib3 & pyOpenSSL librariesSeveral performance fixesBetter parsing of etcd_index and raft_indexRemoved duplicated testsAdded several integration and unit testsUse etcd v0.3.0 in travisExecute test usingpython setup.py testand nose0.3.0Release date: 18-Jan-2014API v2 supportPython 3.3 compatibility0.2.1Release data: 30-Nov-2013SSL supportAdded support for subdirectories in results.Improve testAdded support for reconnections, allowing death node tolerance.0.2.0Release date: 30-Sep-2013Allow fetching of multiple keys (sub-nodes)0.1Release date: 18-Sep-2013Initial release