Reference guide

class aetcd.client.Alarm(alarm_type, member_id)[source]

A cluster member alarm.

Parameters:
  • alarm_type – Type of the alarm.

  • member_id – Cluster member ID.

class aetcd.client.Client(host: str = 'localhost', port: int = 2379, username: str | None = None, password: str | None = None, timeout: int | None = None, options: Dict[str, Any] | None = None, connect_wait_timeout: int = 3)[source]

Client provides and manages a client session.

The client can be used as an async context manager.

Parameters:
  • host (str) – etcd host address, as IP address or a domain name.

  • port (int) – etcd port number to connect to.

  • username (str) – The name of the user used for authentication.

  • password (str) – Password to be used for authentication.

  • timeout (int) – Connection timeout in seconds.

  • options (dict) – Options provided to the underlying gRPC channel.

  • connect_wait_timeout (int) – Connecting wait timeout, since connection could be initiated from multiple coroutines.

Returns:

A Client instance.

async connect() None[source]

Establish a connection to an etcd.

async close() None[source]

Close established connection and frees allocated resources.

It could be called while other operation is being executed.

async get(key: bytes, serializable: bool = False) Get | None[source]

Get a single key from the key-value store.

Parameters:
  • key (bytes) – Key in etcd to get.

  • serializable (bool) – Whether to allow serializable reads. This can result in stale reads.

Returns:

A instance of Get or None, if the the key was not found.

Usage example:

import aetcd
client = aetcd.Client()
await client.get(b'key')
async get_prefix(key_prefix: bytes, sort_order: str | None = None, sort_target: str = 'key', keys_only: bool = False) GetRange[source]

Get a range of keys with a prefix from the key-value store.

Parameters:

key_prefix (bytes) – Key prefix to get.

Returns:

An instance of GetRange.

async get_range(range_start: bytes, range_end: bytes, sort_order: str | None = None, sort_target: str = 'key') GetRange[source]

Get a range of keys from the key-value store.

Parameters:
  • range_start (bytes) – First key in range.

  • range_end (bytes) – Last key in range.

Returns:

An instance of GetRange.

async get_all(sort_order=None, sort_target='key', keys_only=False) GetRange[source]

Get all keys from the key-value store.

Returns:

An instance of GetRange.

async put(key: bytes, value: bytes, lease: int | Lease | None = None, prev_kv: bool = False) Put[source]

Put the given key into the key-value store.

Parameters:
  • key (bytes) – Key in etcd to set.

  • value (bytes) – Value to set key to.

  • lease (either Lease, or int (ID of a lease), or None) – Lease to associate with this key.

  • prev_kv (bool) – Whether to return the previous key-value pair.

Returns:

A instance of Put.

Usage example:

import aetcd
client = aetcd.Client()
await client.put(b'key', b'value')
async delete(key: bytes, prev_kv: bool = False) Delete | None[source]

Delete a single key from the key-value store.

Parameters:
  • key (bytes) – Key in etcd to delete.

  • prev_kv (bool) – Whether to return the deleted key-value pair.

Returns:

A instance of Delete or None, if the the key was not found.

Usage example:

import aetcd
client = aetcd.Client()
await client.put(b'key', b'value')
await client.delete(b'key')
async delete_prefix(key_prefix: bytes, prev_kv: bool = False) DeleteRange[source]

Delete a range of keys with a prefix from the key-value store.

Parameters:
  • key_prefix (bytes) – Key prefix to delete.

  • prev_kv (bool) – Whether to return deleted key-value pairs.

Returns:

An instance of DeleteRange.

async delete_range(range_start: bytes, range_end: bytes, prev_kv: bool = False) DeleteRange[source]

Delete a range of keys from the key-value store.

Parameters:
  • range_start (bytes) – First key in range.

  • range_end (bytes) – Last key in range.

  • prev_kv (bool) – Whether to return deleted key-value pairs.

Returns:

An instance of DeleteRange.

async replace(key: bytes, initial_value: bytes, new_value: bytes, lease: int | Lease | None = None)[source]

Atomically replace the value of a key with a new value.

This compares the current value of a key, then replaces it with a new value if it is equal to a specified value. This operation takes place in a transaction.

Parameters:
  • key – Key in etcd to replace.

  • initial_value (bytes) – Old value to replace.

  • new_value (bytes) – New value of the key

  • lease (either Lease, or int (ID of a lease), or None) – Lease to associate with this key.

Returns:

A status of transaction, True if the replace was successful, False otherwise.

async watch(key: bytes, range_end: bytes | None = None, start_revision: int | None = None, progress_notify: bool = False, kind: EventKind | None = None, prev_kv: bool = False, watch_id: int | None = None, fragment: bool = False)[source]

Watch a key.

Parameters:
  • key (bytes) – Key to watch.

  • range_end (bytes) – 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 x00, 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.

  • start_revision (int) – Revision to watch from (inclusive).

  • progress_notify (bool) – If set, the server will periodically send a response with no events to the new watcher if there are no recent events.

  • kind (aetcd.rtypes.EventKind) – Filter the events by EventKind, at server side before it sends back to the watcher.

  • prev_kv (bool) – If set, created watcher gets the previous key-value before the event happend. If the previous key-value is already compacted, nothing will be returned.

  • watch_id (int) – If provided and non-zero, it will be assigned as ID to this watcher.

  • fragment (bool) – Enable splitting large revisions into multiple watch responses.

Returns:

A instance of Watch.

Usage example:

async for event in await client.watch(b'key'):
    print(event)
async watch_prefix(key_prefix: bytes, range_end: bytes | None = None, start_revision: int | None = None, progress_notify: bool = False, kind: EventKind | None = None, prev_kv: bool = False, watch_id: int | None = None, fragment: bool = False)[source]

Watch a range of keys with a prefix.

Parameters:
  • key_prefix (bytes) – Key prefix to watch.

  • range_end (bytes) – 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 x00, 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.

  • start_revision (int) – Revision to watch from (inclusive).

  • progress_notify (bool) – If set, the server will periodically send a response with no events to the new watcher if there are no recent events.

  • kind (aetcd.rtypes.EventKind) – Filter the events by EventKind, at server side before it sends back to the watcher.

  • prev_kv (bool) – If set, created watcher gets the previous key-value before the event happend. If the previous key-value is already compacted, nothing will be returned.

  • watch_id (int) – If provided and non-zero, it will be assigned as ID to this watcher.

  • fragment (bool) – Enable splitting large revisions into multiple watch responses.

Returns:

A instance of Watch.

async watch_once(key: bytes, timeout: int | None = None, range_end: bytes | None = None, start_revision: int | None = None, progress_notify: bool = False, kind: EventKind | None = None, prev_kv: bool = False, watch_id: int | None = None, fragment: bool = False)[source]

Watch a key and stops after the first event.

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

Parameters:
  • key (bytes) – Key to watch.

  • range_end (bytes) – 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 x00, 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.

  • start_revision (int) – Revision to watch from (inclusive).

  • progress_notify (bool) – If set, the server will periodically send a response with no events to the new watcher if there are no recent events.

  • kind (aetcd.rtypes.EventKind) – Filter the events by EventKind, at server side before it sends back to the watcher.

  • prev_kv (bool) – If set, created watcher gets the previous key-value before the event happend. If the previous key-value is already compacted, nothing will be returned.

  • watch_id (int) – If provided and non-zero, it will be assigned as ID to this watcher.

  • fragment (bool) – Enable splitting large revisions into multiple watch responses.

Returns:

An instance of Event.

async watch_prefix_once(key_prefix: bytes, timeout: int | None = None, range_end: bytes | None = None, start_revision: int | None = None, progress_notify: bool = False, kind: EventKind | None = None, prev_kv: bool = False, watch_id: int | None = None, fragment: bool = False)[source]

Watch a range of keys with a prefix and stops after the first event.

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

Parameters:
  • key_prefix (bytes) – Key prefix to watch.

  • range_end (bytes) – 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 x00, 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.

  • start_revision (int) – Revision to watch from (inclusive).

  • progress_notify (bool) – If set, the server will periodically send a response with no events to the new watcher if there are no recent events.

  • kind (aetcd.rtypes.EventKind) – Filter the events by EventKind, at server side before it sends back to the watcher.

  • prev_kv (bool) – If set, created watcher gets the previous key-value before the event happend. If the previous key-value is already compacted, nothing will be returned.

  • watch_id (int) – If provided and non-zero, it will be assigned as ID to this watcher.

  • fragment (bool) – Enable splitting large revisions into multiple watch responses.

Returns:

An instance of Event.

async transaction(compare, success=None, failure=None)[source]

Perform a transaction.

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).

Usage example:

await client.transaction(
    compare=[
        client.transactions.value(b'key') == b'value',
        client.transactions.version(b'key') > 0,
    ],
    success=[
        client.transactions.put(b'key', b'success'),
    ],
    failure=[
        client.transactions.put(b'key', b'failure'),
    ]
)
async lease(ttl, lease_id=None)[source]

Create a new lease.

All keys attached to this lease will be expired and deleted if the lease expires. A lease can be sent keep alive messages to refresh the ttl.

Parameters:
  • ttl (int) – Requested time to live.

  • lease_id – Requested ID for the lease.

Returns:

A new lease, an instance of Lease.

async revoke_lease(lease_id)[source]

Revoke a lease.

Parameters:

lease_id – ID of the lease to revoke.

lock(key: bytes, ttl: int = 60)[source]

Create a new lock.

Parameters:
  • key (bytes) – The key under which the lock will be stored.

  • ttl (int) – Length of time for the lock to live for in seconds. The lock will be released after this time elapses, unless refreshed.

Returns:

A new lock, an instance of Lock.

async status()[source]

Get the status of the responding member.

async add_member(urls)[source]

Add a member into the cluster.

Returns:

A new member, an instance of Member.

async remove_member(member_id)[source]

Remove an existing member from the cluster.

Parameters:

member_id – ID of the member to remove.

async update_member(member_id, peer_urls)[source]

Update the configuration of an existing member in the cluster.

Parameters:
  • member_id – ID of the member to update.

  • peer_urls – New list of peer URLs the member will use to communicate with the cluster.

async members()[source]

List of all members associated with the cluster.

Returns:

A sequence of Member.

async compact(revision, physical=False)[source]

Compact the event history in etcd up to a given revision.

All superseded keys with a revision less than the compaction revision will be removed.

Parameters:
  • revision – Revision for the compaction operation.

  • physical – If set to True, the request will wait until the compaction is physically applied to the local database such that compacted entries are totally removed from the backend database.

async defragment()[source]

Defragment a member’s backend database to recover storage space.

async hash()[source]

Return the hash of the local KV state.

Returns:

KV state hash.

async create_alarm(member_id=0)[source]

Create an alarm.

If no member id is given, the alarm is activated for all the members of the cluster. Only the no space alarm can be raised.

Parameters:

member_id – The cluster member ID to create an alarm to. If 0, the alarm is created for all the members of the cluster.

Returns:

A sequence of Alarm.

async list_alarms(member_id=0, alarm_type='none')[source]

List the activated alarms.

Parameters:
  • member_id – The cluster member ID.

  • alarm_type – The cluster member ID to create an alarm to. If 0, the alarm is created for all the members of the cluster.

Returns:

A sequence of Alarm.

async disarm_alarm(member_id=0)[source]

Cancel an alarm.

Parameters:

member_id – The cluster member id to cancel an alarm. If 0, the alarm is canceled for all the members of the cluster.

Returns:

A sequence of Alarm.

async snapshot(file_obj)[source]

Take a snapshot of the database.

Parameters:

file_obj – A file-like object to write the database contents in.

exception aetcd.exceptions.ClientError[source]

The most generic client error.

exception aetcd.exceptions.ConnectionFailedError[source]

Raises on etcd server connection errors.

exception aetcd.exceptions.ConnectionTimeoutError[source]

Raises on etcd server connection timeout errors.

exception aetcd.exceptions.InternalError[source]

Raises on etcd internal errors.

exception aetcd.exceptions.InvalidArgumentError[source]

Raises on errors associated with incorrect arguments being provided.

exception aetcd.exceptions.UnauthenticatedError[source]

Raises on etcd unauthenticated errors.

exception aetcd.exceptions.PreconditionFailedError[source]

Raises on etcd server precondition errors.

exception aetcd.exceptions.DuplicateLeaseError[source]

Raises on attempt to create a lease with already existing ID.

exception aetcd.exceptions.RevisionCompactedError(compacted_revision)[source]

Raises when requested and previous revisions were already compacted.

compacted_revision

Revision bellow values were compacted.

exception aetcd.exceptions.WatchTimeoutError[source]

Raises on watch operation timeouts.

Please note, this error is different from ConnectionTimeoutError and may be raised only in two cases: when watch create operation was not completed in time and when watch event was not emitted within provided timeout.

class aetcd.leases.Lease(lease_id, ttl, etcd_client)[source]

A lease.

Parameters:
  • id – ID of the lease

  • ttl – time to live for this lease

  • etcd_client – Instance of aetcd.client.Client

async revoke()[source]

Revoke this lease.

async refresh()[source]

Refresh the time to live for this lease.

async remaining_ttl()[source]

Return remaining time to live for this lease.

async granted_ttl()[source]

Return granted time to live for this lease.

async keys()[source]

Return list of keys associated with this lease.

class aetcd.locks.Lock(client, key: bytes, ttl: int)[source]

A distributed lock.

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

client = aetcd.Client()

# Create a lock that expires after 20 seconds
with client.lock(b'key', ttl=20) as lock:
    # do something that requires the lock
    print(lock.is_acquired())

    # refresh the timeout on the lease
    lock.refresh()
Parameters:
  • client (aetcd.client.Client) – An instance of Client

  • key (bytes) – The key under which the lock will be stored.

  • ttl (int) – Length of time for the lock to live for in seconds. The lock will be released after this time elapses, unless refreshed.

async acquire(timeout: int = 10)[source]

Acquire the lock.

Parameters:

timeout (int) – 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.

async release()[source]

Release the lock.

async refresh()[source]

Refresh the time to live on this lock.

async is_acquired()[source]

Check if this lock is currently acquired.

class aetcd.members.Member(id, name, peer_urls, client_urls, etcd_client)[source]

A member of the etcd cluster.

Parameters:
  • id – ID of the cluster member

  • name – Human-readable name of the cluster member

  • peer_urls – List of URLs the cluster member exposes to the cluster for communication

  • client_urls – List of URLs the cluster member exposes to clients for communication

  • etcd_client – Instance of aetcd.client.Client

async remove()[source]

Remove this cluster member from the cluster.

async update(peer_urls)[source]

Update the configuration of this cluster member.

Parameters:

peer_urls – New list of peer URLs the cluster member will use to communicate with the cluster

async active_alarms()[source]

Get active alarms of the cluster member.

Returns:

List of aetcd.client.Alarm

class aetcd.rtypes.ResponseHeader(header)[source]

Represents the metadata for the response.

cluster_id: int

The ID of the cluster which sent the response.

member_id: int

The ID of the member which sent the response.

revision: int

The key-value store revision when the request was applied. For watch progress responses, the revision indicates progress. All future events recieved in this stream are guaranteed to have a higher revision number than the revision number.

raft_term: int

The raft term when the request was applied.

class aetcd.rtypes.KeyValue(keyvalue)[source]

Represents the requested key-value.

key: bytes

Key in bytes, empty key is not allowed.

value: bytes

Value held by the key, in bytes.

create_revision: int

Revision of last creation on this key.

mod_revision: int

Revision of last modificatioin on this key.

version: int

Version of the key, a deletion resets the version to zero and any modification of the key increases its version.

lease: int

ID of the lease that attached to the key, when the attached lease expires, the key will be deleted, if the lease is zero, then no lease is attached to the key.

class aetcd.rtypes.Get(header, keyvalue)[source]

Represents the result of get operation.

header: ResponseHeader

Response header.

key: bytes

Key in bytes, empty key is not allowed.

value: bytes

Value held by the key, in bytes.

create_revision: int

Revision of last creation on this key.

mod_revision: int

Revision of last modificatioin on this key.

version: int

Version of the key, a deletion resets the version to zero and any modification of the key increases its version.

lease: int

ID of the lease that attached to the key, when the attached lease expires, the key will be deleted, if the lease is zero, then no lease is attached to the key.

class aetcd.rtypes.GetRange(header, kvs, more, count)[source]

Represents the result of get range operation.

Implements __bool__, __len__, __iter__ and __getitem__.

If a number of count keys is above zero iterpret the result as truthy, otherwise as falsy.

It is possible to iterate over the collection or use indexing, as a result KeyValue will be returned.

Note

Also, it is possible to access raw kvs provided by the underlying RPC call, that is the most effective way to access the keys from performance and memory perspective, but keep in mind that the overall performance highly depends on usage pattern and the size of dataset, use wisely. Generally, it is recommended to use KeyValue wrapped results.

header: ResponseHeader

Response header.

kvs

The list of key-value pairs matched by the range request, empty when count_only flag was set in the request.

more: bool

Indicates if there are more keys to return in the requested range.

count: int

The number of keys within the requested range.

class aetcd.rtypes.Put(header, prev_kv=None)[source]

Represents the result of put operation.

header: ResponseHeader

Response header.

prev_kv: KeyValue | None

If prev_kv flag was set in the request, the previous key-value pair will be stored in this attribute.

class aetcd.rtypes.Delete(header, deleted, prev_kv=None)[source]

Represents the result of delete operation.

header: ResponseHeader

Response header.

deleted: int

The number of keys deleted by the delete request.

prev_kv: KeyValue | None

If prev_kv flag was set in the request, the previous key-value pair will be stored in this attribute.

class aetcd.rtypes.DeleteRange(header, deleted, prev_kvs)[source]

Represents the result of delete range operation.

Implements __bool__, __len__, __iter__ and __getitem__.

If a number of deleted keys is above zero iterpret the result as truthy, otherwise as falsy.

It is possible to iterate over the collection or use indexing, as a result KeyValue will be returned.

Note

Also, it is possible to access raw prev_kvs provided by the underlying RPC call, that is the most effective way to access the keys from performance and memory perspective, but keep in mind that the overall performance highly depends on usage pattern and the size of dataset, use wisely. Generally, it is recommended to use KeyValue wrapped results.

header: ResponseHeader

Response header.

deleted: int

The number of keys deleted by the delete request.

prev_kvs

The list of deleted key-value pairs matched by the delete range request, filled when prev_kv flag was set in the request, otherwise empty.

class aetcd.rtypes.EventKind(value)[source]

An enumeration.

PUT = 'PUT'

Designates a PUT event.

DELETE = 'DELETE'

Designates a DELETE event.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

replace(old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including \n \r \t \f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits (starting from the left). -1 (the default value) means no limit.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including \n \r \t \f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits (starting from the left). -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

index(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

rfind(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

startswith(prefix[, start[, end]]) bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

endswith(suffix[, start[, end]]) bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

format(*args, **kwargs) str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping) str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

class aetcd.rtypes.Event(kind, kv, prev_kv=None)[source]

Reperesents a watch event.

kind: EventKind

The kind of event. If the type is a PUT, it indicates new data has been stored to the key. If the type is a DELETE, it indicates the key was deleted.

kv: KeyValue

Holds the key-value for the event. A PUT event contains current key-value pair. A PUT event with version that equals to 1 indicates the creation of a key. A DELETE event contains the deleted key with its modification revision set to the revision of deletion.

prev_kv: KeyValue | None

Holds the key-value pair before the event happend.

class aetcd.rtypes.Watch(iterator, cancel_func, watch_id)[source]

Reperesents the result of a watch operation.

To get emitted events use as an asynchronous iterator, emitted events are instances of an Event.

Usage example:

async for event in client.watch(b'key'):
    print(event)
watch_id: int

The ID of the watcher that emits the events.

async cancel()[source]

Cancel the watcher so that no more events are emitted.

aetcd.utils.prefix_range_end(prefix: bytes) bytes[source]

Create a bytestring that can be used as a range_end for a prefix.

aetcd.utils.to_bytes(maybe_bytes: bytes | str) bytes[source]

Encode string to bytes.

Convenience function to do a simple encode('utf-8') if the input is not already bytes, return the data unmodified if the input is bytes.

aetcd.utils.lease_to_id(lease: Lease | int) int[source]

Resolve lease ID based on the provided argument.

If provided argument is a Lease object, just return its ID, otherwise cast provided argument to int and return the result or 0 if the cast failed.

class aetcd.watcher.WatcherCallback(callback: Callable)[source]

Represents the result of a callback watch operation.

callback: Callable

A callback function that will be called when new events are emitted.

watch_id: int | None

ID of the watcher.

prev_kv: bool

Get the previous key-value before the event happend.

error: Exception | None

Error that was raised by the underlying machinery, if any.

class aetcd.watcher.Watcher(watchstub, timeout=None, metadata=None)[source]

Watch for events happening or that have happened.

One watcher can watch on multiple key ranges, streaming events for several watches at once. The entire event history can be watched starting from the last compaction revision.

Note

The implementation is mostly for internal use, it is advised to use appropriate client watch methods.

async setup()[source]

Set up the watcher.

async shutdown()[source]

Shutdown the watcher.

async add_callback(key: bytes, callback: Callable, range_end: bytes | None = None, start_revision: int | None = None, progress_notify: bool = False, kind: EventKind | None = None, prev_kv: bool = False, watch_id: int | None = None, fragment: bool = False) WatcherCallback[source]

Add a callback that will be called when new events are emitted.

Parameters:
  • key (bytes) – Key to watch.

  • callback (callable) – Callback function.

  • range_end (bytes) – 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 x00, 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.

  • start_revision (int) – Revision to watch from (inclusive).

  • progress_notify (bool) – If set, the server will periodically send a response 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 server may decide how often it will send notifications based on the current load.

  • kind (aetcd.rtypes.EventKind) – Filter the events by EventKind, at server side before it sends back to the watcher.

  • prev_kv (bool) – If set, created watcher gets the previous key-value before the event happend. If the previous key-value is already compacted, nothing will be returned.

  • watch_id (int) – If provided and non-zero, it will be assigned as ID to this watcher. Since creating a watcher in etcd is not a synchronous operation, this can be used ensure that ordering is correct when creating multiple watchers on the same stream. Creating a watcher with an ID already in use on the stream will cause an error to be returned.

  • fragment (bool) – Enable splitting large revisions into multiple watch responses.

Returns:

A instance of WatcherCallback.

async cancel(watch_id: int) None[source]

Cancel the watcher so that no more events are emitted.

Parameters:

watch_id (int) – The ID of the watcher to cancel.