API Reference

etcd3.baseclient

synchronous client

class etcd3.baseclient.BaseModelizedStreamResponse[source]

Bases: object

Model of a stream response

close()[source]

close the stream

class etcd3.baseclient.BaseClient(host='127.0.0.1', port=2379, protocol='http', cert=(), verify=None, timeout=None, headers=None, user_agent=None, pool_size=30, username=None, password=None, token=None, server_version='3.3.0', cluster_version='3.3.0')[source]

Bases: etcd3.apis.auth.AuthAPI, etcd3.apis.cluster.ClusterAPI, etcd3.apis.kv.KVAPI, etcd3.apis.lease.LeaseAPI, etcd3.apis.maintenance.MaintenanceAPI, etcd3.apis.watch.WatchAPI, etcd3.apis.extra.ExtraAPI, etcd3.apis.lock.LockAPI

__init__(host='127.0.0.1', port=2379, protocol='http', cert=(), verify=None, timeout=None, headers=None, user_agent=None, pool_size=30, username=None, password=None, token=None, server_version='3.3.0', cluster_version='3.3.0')[source]

Initialize self. See help(type(self)) for accurate signature.

baseurl
Returns:baseurl from protocol, host, self
__enter__()[source]
__exit__(*args)[source]
close()[source]

close all connections in connection pool

call_rpc(method, data=None, stream=False, encode=True, raw=False, **kwargs)[source]

call ETCDv3 RPC and return response object

Parameters:
  • method (str) – the rpc method, which is a path of RESTful API
  • data (dict) – request payload to be post to ETCD’s gRPC-JSON-Gateway default: {}
  • stream (bool) – whether return a stream response object, default: False
  • encode (bool) – whether encode the data before post, default: True
  • kwargs – additional params to pass to the http request, like headers, timeout etc.
Returns:

Etcd3RPCResponseModel or Etcd3StreamingResponse

auth(username=None, password=None)[source]

call auth.authenticate and save the token

Parameters:
  • username (str) – username
  • password (str) – password
Txn()[source]

Initialize a Transaction

Lease(ttl, ID=0, new=True)[source]

Initialize a Lease

Parameters:
  • ID (int) – ID is the requested ID for the lease. If ID is set to 0, the lessor chooses an ID.
  • new (bool) – whether grant a new lease or maintain a exist lease by its id [default: True]
Watcher(key=None, range_end=None, max_retries=-1, start_revision=None, progress_notify=None, prev_kv=None, prefix=None, all=None, no_put=False, no_delete=False)[source]

Initialize a Watcher

Parameters:
  • key (str or bytes) – key is the key to register for watching.
  • range_end (str or bytes) – range_end is the end of the range [key, range_end) to watch. If range_end is not given, only the key argument is watched. If range_end is equal to ‘’, all keys greater than or equal to the key argument are watched. If the range_end is one bit larger than the given key, then all keys with the prefix (the given key) will be watched.
  • max_retries (int) – max retries when watch failed due to network problem, -1 means no limit [default: -1]
  • start_revision (int) – start_revision is an optional revision to watch from (inclusive). No start_revision is “now”.
  • progress_notify (bool) – progress_notify is set so that the etcd server will periodically send a WatchResponse with no events to the new watcher if there are no recent events. It is useful when clients wish to recover a disconnected watcher starting from a recent known revision. The etcd server may decide how often it will send notifications based on current load.
  • prev_kv (bool) – If prev_kv is set, created watcher gets the previous KV before the event happens. If the previous KV is already compacted, nothing will be returned.
  • prefix (bool) – if the key is a prefix [default: False]
  • all (bool) – all the keys [default: False]
  • no_put (bool) – filter out the put events at server side before it sends back to the watcher. [default: False]
  • no_delete (bool) – filter out the delete events at server side before it sends back to the watcher. [default: False]
Returns:

Watcher

Lock(lock_name, lock_ttl=60, reentrant=None, lock_prefix='_locks')[source]

etcd3.client

synchronous client

class etcd3.client.ModelizedStreamResponse(client, method, resp, decode=True)[source]

Bases: etcd3.baseclient.BaseModelizedStreamResponse

Model of a stream response

__init__(client, method, resp, decode=True)[source]
Parameters:resp – Response
raw
close()[source]

close the stream

__enter__()[source]
__exit__(exc_type, exc_val, exc_tb)[source]
etcd3.client.iter_response(resp)[source]

yield response content by every json object we don’t yield by line, because the content of etcd’s gRPC-JSON-Gateway stream response does not have a delimiter between each object by default. (only one line)

https://github.com/grpc-ecosystem/grpc-gateway/pull/497/files

Parameters:resp – Response
Returns:dict
class etcd3.client.Client(host='127.0.0.1', port=2379, protocol='http', cert=(), verify=None, timeout=None, headers=None, user_agent=None, pool_size=30, username=None, password=None, token=None, max_retries=0, server_version='3.3.0', cluster_version='3.3.0')[source]

Bases: etcd3.baseclient.BaseClient

__init__(host='127.0.0.1', port=2379, protocol='http', cert=(), verify=None, timeout=None, headers=None, user_agent=None, pool_size=30, username=None, password=None, token=None, max_retries=0, server_version='3.3.0', cluster_version='3.3.0')[source]
Parameters:max_retries – The maximum number of retries each connection should attempt. Note, this applies only to failed DNS lookups, socket connections and connection timeouts, never to requests where data has made it to the server. By default, Requests does not retry failed connections. If you need granular control over the conditions under which we retry a request, import urllib3’s Retry class and pass that instead.
close()[source]

close all connections in connection pool

call_rpc(method, data=None, stream=False, encode=True, raw=False, **kwargs)[source]

call ETCDv3 RPC and return response object

Parameters:
  • method (str) – the rpc method, which is a path of RESTful API
  • data (dict) – request payload to be post to ETCD’s gRPC-JSON-Gateway default: {}
  • stream (bool) – whether return a stream response object, default: False
  • encode (bool) – whether encode the data before post, default: True
  • kwargs – additional params to pass to the http request, like headers, timeout etc.
Returns:

Etcd3RPCResponseModel or Etcd3StreamingResponse

auth(username=None, password=None)[source]

call auth.authenticate and save the token

Parameters:
  • username (str) – username
  • password (str) – password

etcd3.aio_client

asynchronous client

class etcd3.aio_client.ModelizedResponse(client, method, resp, decode=True)[source]

Bases: object

__init__(client, method, resp, decode=True)[source]

Initialize self. See help(type(self)) for accurate signature.

class etcd3.aio_client.ModelizedStreamResponse(client, method, resp, decode=True)[source]

Bases: etcd3.baseclient.BaseModelizedStreamResponse

Model of a stream response

__init__(client, method, resp, decode=True)[source]
Parameters:resp – aiohttp.ClientResponse
connection
resp_iter
close()[source]

close the stream

__enter__()[source]
__exit__(exc_type, exc_val, exc_tb)[source]
__aenter__()[source]
__aexit__(exc_type, exc_val, exc_tb)[source]
class etcd3.aio_client.ResponseIter(resp)[source]

Bases: object

yield response content by every json object we don’t yield by line, because the content of etcd’s gRPC-JSON-Gateway stream response does not have a delimiter between each object by default. (only one line)

https://github.com/grpc-ecosystem/grpc-gateway/pull/497/files

Parameters:resp – aiohttp.ClientResponse
Returns:dict
__init__(resp)[source]

Initialize self. See help(type(self)) for accurate signature.

next()[source]
class etcd3.aio_client.AioClient(host='127.0.0.1', port=2379, protocol='http', cert=(), verify=None, timeout=None, headers=None, user_agent=None, pool_size=30, username=None, password=None, token=None, server_version='3.3.0', cluster_version='3.3.0')[source]

Bases: etcd3.baseclient.BaseClient

__init__(host='127.0.0.1', port=2379, protocol='http', cert=(), verify=None, timeout=None, headers=None, user_agent=None, pool_size=30, username=None, password=None, token=None, server_version='3.3.0', cluster_version='3.3.0')[source]

Initialize self. See help(type(self)) for accurate signature.

session
call_rpc(method, data=None, stream=False, encode=True, raw=False, **kwargs)[source]

call ETCDv3 RPC and return response object

Parameters:
  • method (str) – the rpc method, which is a path of RESTful API
  • data (dict or str) – request payload to be post to ETCD’s gRPC-JSON-Gateway default: {}
  • stream (bool) – whether return a stream response object, default: False
  • encode (bool) – whether encode the data before post, default: True
  • kwargs – additional params to pass to the http request, like headers, timeout etc.
Returns:

Etcd3RPCResponseModel or Etcd3StreamingResponse

__aenter__()[source]
__aexit__(exc_type, exc_val, exc_tb)[source]
auth(username=None, password=None)[source]

call auth.authenticate and save the token

Parameters:
  • username (str) – username
  • password (str) – password
close()[source]

close all connections in connection pool

etcd3.models

class etcd3.models.EtcdModel[source]

Bases: object

class etcd3.models.AlarmRequestAlarmAction

Bases: etcd3.models.EtcdModel, enum.Enum

ref: #/definitions/AlarmRequestAlarmAction

default: GET

ACTIVATE = 'ACTIVATE'
DEACTIVATE = 'DEACTIVATE'
GET = 'GET'
class etcd3.models.CompareCompareResult

Bases: etcd3.models.EtcdModel, enum.Enum

ref: #/definitions/CompareCompareResult

default: EQUAL

EQUAL = 'EQUAL'
GREATER = 'GREATER'
LESS = 'LESS'
NOT_EQUAL = 'NOT_EQUAL'
class etcd3.models.CompareCompareTarget

Bases: etcd3.models.EtcdModel, enum.Enum

ref: #/definitions/CompareCompareTarget

default: VERSION

CREATE = 'CREATE'
LEASE = 'LEASE'
MOD = 'MOD'
VALUE = 'VALUE'
VERSION = 'VERSION'
class etcd3.models.EventEventType

Bases: etcd3.models.EtcdModel, enum.Enum

ref: #/definitions/EventEventType

default: PUT

DELETE = 'DELETE'
PUT = 'PUT'
class etcd3.models.RangeRequestSortOrder

Bases: etcd3.models.EtcdModel, enum.Enum

ref: #/definitions/RangeRequestSortOrder

default: NONE

ASCEND = 'ASCEND'
DESCEND = 'DESCEND'
NONE = 'NONE'
class etcd3.models.RangeRequestSortTarget

Bases: etcd3.models.EtcdModel, enum.Enum

ref: #/definitions/RangeRequestSortTarget

default: KEY

CREATE = 'CREATE'
KEY = 'KEY'
MOD = 'MOD'
VALUE = 'VALUE'
VERSION = 'VERSION'
class etcd3.models.WatchCreateRequestFilterType

Bases: etcd3.models.EtcdModel, enum.Enum

ref: #/definitions/WatchCreateRequestFilterType

default: NOPUT

NODELETE = 'NODELETE'
NOPUT = 'NOPUT'
class etcd3.models.authpbPermissionType

Bases: etcd3.models.EtcdModel, enum.Enum

ref: #/definitions/authpbPermissionType

default: READ

READ = 'READ'
READWRITE = 'READWRITE'
WRITE = 'WRITE'
class etcd3.models.etcdserverpbAlarmType

Bases: etcd3.models.EtcdModel, enum.Enum

ref: #/definitions/etcdserverpbAlarmType

default: NONE

CORRUPT = 'CORRUPT'
NONE = 'NONE'
NOSPACE = 'NOSPACE'

etcd3.swagger_helper

etcd3.swagger_helper.swagger_escape(s)[source]

/ and ~ are special characters in JSON Pointers, and need to be escaped when used literally (for example, in path names).

https://swagger.io/docs/specification/using-ref/#escape

class etcd3.swagger_helper.SwaggerSpec(spec)[source]

Bases: object

Parse the swagger spec of gRPC-JSON-Gateway to object tree

__init__(spec)[source]
Parameters:spec – dict or json string or yaml string
ref(ref_path)[source]

get the node object from absolute reference

Parameters:ref_path – str
Returns:SwaggerNode

example:

>>> spec.ref('#/definitions/etcdserverpbAlarmResponse')
SwaggerSchema(ref='#/definitions/etcdserverpbAlarmResponse')
get(key, *args, **kwargs)[source]

equivariant to self.spec.get(key)

getPath(key)[source]

get a SwaggerPath instance of the path

Parameters:key (SwaggerNode or str) – receive a SwaggerNode or a $ref string of schema
Return type:SwaggerNode
getSchema(key)[source]

get a SwaggerSchema instance of the schema

Parameters:key (SwaggerNode or str) – receive a SwaggerNode or a $ref string of schema
Return type:SwaggerNode
getEnum(key)[source]

get a Enum instance of the schema

Parameters:key (SwaggerNode or str) – receive a SwaggerNode or a $ref string of schema
Return type:SwaggerNode
class etcd3.swagger_helper.SwaggerNode(root, node, path, parent=None, name=None)[source]

Bases: object

the node of swagger_spec object

can represent a path, a schema or a ordinary node

as a schema, it can generate a model object of the definition, decode or encode the payload

__init__(root, node, path, parent=None, name=None)[source]

Initialize self. See help(type(self)) for accurate signature.

encode(data)[source]

encode the data to as the schema defined

Parameters:data – data to encode
Returns:encoded data
decode(data)[source]

decode the data as the schema defined

Parameters:data – data to decode
Returns:decoded data
getModel()[source]

get the model of the schema

Null handling:

Since etcd’s swagger spec is converted from gogoproto files, modelizing will follow the gogoprotobuf deserialization rule:

int -> 0 bool -> False object -> None array -> None string -> “”

etcd3.utils

etcd3.utils.lru_cache(maxsize=100)[source]

Least-recently-used cache decorator.

If maxsize is set to None, the LRU features are disabled and the cache can grow without bound.

Arguments to the cached function must be hashable.

View the cache statistics named tuple (hits, misses, maxsize, currsize) with f.cache_info(). Clear the cache and statistics with f.cache_clear(). Access the underlying function with f.__wrapped__.

See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used

etcd3.utils.memoize(fn)[source]

Decorator. Caches a function’s return value each time it is called. If called later with the same arguments, the cached value is returned (not reevaluated).

etcd3.utils.memoize_in_object(fn)[source]

Decorator. Caches a method’s return value each time it is called, in the object instance If called later with the same arguments, the cached value is returned (not reevaluated).

etcd3.utils.incr_last_byte(data)[source]

Get the last byte in the array and increment it

etcd3.utils.merge_two_dicts(x, y)[source]
etcd3.utils.check_param(at_least_one_of=None, at_most_one_of=None)[source]

check if at least/most one of params is given

>>> @check_param(at_least_one_of=['a', 'b'])
>>> def fn(a=None, b=None):
...     pass
>>> fn()
TypeError: fn() requires at least one argument of a,b
etcd3.utils.run_coro(coro)[source]
Parameters:coro (asyncio.coroutine) – the coroutine to run
class etcd3.utils.cached_property(func)[source]

Bases: object

A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property.

Source: https://github.com/bottlepy/bottle/blob/0.11.5/bottle.py#L175

__init__(func)[source]

Initialize self. See help(type(self)) for accurate signature.

etcd3.utils.iter_json_string(chunk, start=0, lb=123, rb=125, resp=None, err_cls=<class 'ValueError'>)[source]
etcd3.utils.enum_value(e)[source]
etcd3.utils.retry(func, max_tries=3, log=<module 'logging' from '/home/docs/.pyenv/versions/3.6.8/lib/python3.6/logging/__init__.py'>, err_cls=<class 'Exception'>)[source]
etcd3.utils.exec_cmd(cmd, envs=None, raise_error=True)[source]
exception etcd3.utils.Etcd3Warning[source]

Bases: UserWarning

etcd3.utils.find_executable(executable, path=None)[source]

Find if ‘executable’ can be run. Looks for it in ‘path’ (string that lists directories separated by ‘os.pathsep’; defaults to os.environ[‘PATH’]). Checks for all executable extensions. Returns full path or None if no command is found.

comments powered by Disqus