madbot_cli.client
A client of the madbot REST API, authenticated by a personal access token.
The client knows the conventions of the API: the token, the workspace header,
the pages of a list and the background tasks. It knows nothing of nodes or
submissions: madbot_cli.operations builds the steps of a deposit on it.
Every request goes through a transport, a function that sends one HTTP request and returns the status and the body of the answer. The default one uses the standard library; another one can be given, for a proxy or tests.
A request that can be sent again without effect (a read, a PUT, the values of
a metadata object) is sent again when the network drops or a gateway gives
up, after a growing pause: see RETRY_DELAYS. A request that creates is
never sent twice.
Attributes
| Name | Description |
|---|---|
GATEWAY_GAVE_UP | Statuses of a proxy or gateway that did not reach madbot: worth a new attempt. |
LIST_READS | Times a list whose length changes while it is read is read again from its first page. |
MAX_PAGE_SIZE | The largest page the API serves. |
MIN_API_VERSION | The oldest version of the madbot API this release works with. |
OnRetry | Told of a new attempt: (reason, seconds before it, attempt number). |
REDIRECTION_MAX | The first HTTP status after those of a redirection. |
REDIRECTION_MIN | The first HTTP status of a redirection, which the client never follows. |
REPLAYABLE_METHODS | Methods whose repetition has no further effect: they are sent again on a network drop. |
RETRY_DELAYS | Seconds to wait before each new attempt of a request that can be repeated: 31 s of pauses in all, each attempt waiting up to the timeout of the transport. |
TASK_DONE | States of a task over in success. |
TASK_FAILED | States of a task over in failure. |
Transport | A transport sends one request: (method, url, headers, body) -> (status, body). |
Classes
| Name | Description |
|---|---|
Client | A client of the madbot REST API. |
Functions
| Name | Description |
|---|---|
urllib_transport | Make the default transport, built on urllib.request. |
GATEWAY_GAVE_UPattributemodule attribute#
GATEWAY_GAVE_UP = {502, 503, 504}Statuses of a proxy or gateway that did not reach madbot: worth a new attempt.
LIST_READSattributemodule attribute#
LIST_READS = 3Times a list whose length changes while it is read is read again from its first page.
MAX_PAGE_SIZEattributemodule attribute#
MAX_PAGE_SIZE = 500The largest page the API serves.
MIN_API_VERSIONattributemodule attribute#
MIN_API_VERSION = (2, 2, 0)The oldest version of the madbot API this release works with.
OnRetryattributemodule attribute#
OnRetry = Callable[[str, float, int], None]Told of a new attempt: (reason, seconds before it, attempt number).
REDIRECTION_MAXattributemodule attribute#
REDIRECTION_MAX = 400The first HTTP status after those of a redirection.
REDIRECTION_MINattributemodule attribute#
REDIRECTION_MIN = 300The first HTTP status of a redirection, which the client never follows.
REPLAYABLE_METHODSattributemodule attribute#
REPLAYABLE_METHODS = {'GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'}Methods whose repetition has no further effect: they are sent again on a network drop.
RETRY_DELAYSattributemodule attribute#
RETRY_DELAYS = (1, 2, 4, 8, 16)Seconds to wait before each new attempt of a request that can be repeated: 31 s of pauses in all, each attempt waiting up to the timeout of the transport.
TASK_DONEattributemodule attribute#
TASK_DONE = {'SUCCESS'}States of a task over in success.
TASK_FAILEDattributemodule attribute#
TASK_FAILED = {'FAILURE', 'REVOKED'}States of a task over in failure.
Transportattributemodule attribute#
Transport = Callable[[str, str, Mapping[str, str], 'bytes | None'], 'tuple[int, bytes]']A transport sends one request: (method, url, headers, body) -> (status, body).
Clientclass#
class Client(api_url: str, token: str, *, workspace: str | None = None, transport: Transport | None = None, sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic, retry_delays: Sequence[float] = RETRY_DELAYS, on_retry: OnRetry | None = None)A client of the madbot REST API.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
api_url | str | required | The address of the API, such as https://api.madbot.example.org.
It is often not the address of the web application. |
token | str | required | A personal access token of that instance, with the read and write scopes. |
workspace | str | None | The identifier of the workspace the requests act in, sent in the
X-Workspace header. use_workspace sets it later. |
transport | Transport | None | Sends the requests; urllib_transport() by default. |
sleep | callable | time.sleep | Waits between two reads of a background task; time.sleep by default. |
clock | callable | time.monotonic | Measures how long a wait lasts; time.monotonic by default. |
retry_delays | sequence of float | RETRY_DELAYS | Seconds to wait before each new attempt of a request that can be
repeated, when the network drops; RETRY_DELAYS by default, empty
for none. |
on_retry | callable | None | Told of each new attempt, to show it: (reason, seconds before it, attempt number). |
Examples
>>> client = Client.from_env()>>> client.use_workspace("my-workspace")>>> nodes = client.list("/api/nodes")api_urlattributeinstance attribute#
api_url = api_url.rstrip('/')clockattributeinstance attribute#
clock = clockon_retryattributeinstance attribute#
on_retry = on_retryretry_delaysattributeinstance attribute#
retry_delays = tuple(retry_delays)sleepattributeinstance attribute#
sleep = sleeptokenattributeinstance attribute#
token = tokentransportattributeinstance attribute#
transport = transport or urllib_transport()workspaceattributeinstance attribute#
workspace = workspaceattemptmethod#
def attempt(method: str, url: str, headers: Mapping[str, str], body: bytes | None, replayable: bool) -> tuple[int, bytes]Send a request through the transport, again after a pause when it can be repeated.
Parameters
Returns
tuple- The status and the body of the answer.
Raises
ApiUnreachable- When no answer came, after the last attempt.
check_versionmethod#
def check_version() -> dictRead the version of the API and tell whether this release works with it.
Returns
dictversionof madbot, andcompatible: False for a version older thanMIN_API_VERSION, None when it cannot be read.
from_envmethodclassmethod#
def from_env(api_url: str | None = None, token: str | None = None, environ: Mapping[str, str] | None = None, **options: Any) -> ClientMake a client from the MADBOT_API and MADBOT_TOKEN environment variables.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
api_url | str | None | The address of the API; MADBOT_API when not given. |
token | str | None | The personal access token; MADBOT_TOKEN when not given. |
environ | mapping | None | The environment to read; os.environ by default. |
**options | Any | {} | Passed to the client: workspace, transport, sleep, clock,
retry_delays, on_retry. |
Returns
Client- The client.
Raises
MadbotError- When the address or the token is missing, or the address is not http(s). There is no default address, so that nothing is written to an instance by mistake.
getmethod#
def get(path: str, **params: Any) -> AnyRead one object.
Parameters
Returns
Any- The decoded answer.
listmethod#
def list(path: str, *, must_settle: bool = False, **params: Any) -> list[Any]Read every page of a list.
The API makes each page anew: a list that changes between two pages, such as a folder a source lists differently from one request to the next, would come back cut or with an item twice. Each page gives the length of the whole list; when it changes, the list is read again from its first page.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
path | str | required | The path of the list. |
must_settle | bool | False | True for a list that must be read whole, such as a folder of a
source where a name is sought: when its length still changes after
LIST_READS reads, the command stops. Otherwise the last read is
kept, as for the data madbot still links while it is read. |
**params | Any | {} | Query parameters, such as filters. |
Returns
list- All the items of the list.
Raises
MadbotError- With
must_settle, when the length of the list still changes afterLIST_READSreads.
postmethod#
def post(path: str, payload: Any = None, *, replayable: bool = False) -> AnyCreate an object or run an action.
Parameters
Returns
Any- The decoded answer.
read_pagesmethod#
def read_pages(path: str, params: Mapping[str, Any]) -> tuple[list[Any], bool]Read a list once, page after page.
Parameters
| Name | Type | Description |
|---|---|---|
path | str | The path of the list. |
params | mapping | Query parameters, such as filters. |
Returns
tuple- The items read, and whether every page gave the same length of the list.
requestmethod#
def request(method: str, path: str, payload: Any = None, *, params: Mapping[str, Any] | None = None, replayable: bool | None = None) -> AnySend a request and return the decoded answer.
Parameters
Returns
Any- The decoded JSON answer, None when empty.
same_originmethod#
def same_origin(url: str) -> strPut a link of the API back on the address of the client.
Behind a proxy, the API may build its links on another scheme or host
(http:// behind TLS): the token must only go to api_url.
Parameters
| Name | Type | Description |
|---|---|---|
url | str | A full URL given by the API, such as the next page of a list. |
Returns
str- The same path and query, on the scheme and host of
api_url.
sendmethod#
def send(method: str, path: str, payload: Any = None, *, params: Mapping[str, Any] | None = None, replayable: bool | None = None) -> tuple[int, Any]Send a request and return the status with the decoded answer.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
method | str | required | The HTTP method. |
path | str | required | A path under the API address, or a full URL. |
payload | Any | None | The body of the request, sent as JSON. |
params | mapping | None | Query parameters. |
replayable | bool | None | Whether the request can be sent again without effect, when the
network drops; by default, for the methods of REPLAYABLE_METHODS.
Never for a request that creates. |
Returns
tuple- The HTTP status and the decoded JSON answer (None when empty).
Raises
ApiError- A subclass matching the status of an error answer;
ApiUnreachablewithout an answer, once the new attempts are spent;NotJsonwhen the answer is not JSON.
urlmethod#
def url(path: str, params: Mapping[str, Any] | None = None) -> strBuild the URL of a request.
Parameters
Returns
str- The URL.
use_workspacemethod#
def use_workspace(name_slug_or_id: str) -> dictSend the following requests in a workspace of the account.
Parameters
| Name | Type | Description |
|---|---|---|
name_slug_or_id | str | The name, the slug (after /w/ in the address of the web
application) or the identifier of the workspace. |
Returns
dict- The workspace.
Raises
NotFound- When the account has no such workspace.
versionmethod#
def version() -> dictRead the version of the API.
Returns
dictversionof madbot andplugins_api_version.
wait_taskmethod#
def wait_task(task_id: str, *, timeout: float = 1800, interval: float = 2, pending_grace: float = 60, on_wait: Callable[[float], None] | None = None) -> dictWait for a background task of madbot to end.
A task is read with GET /api/tasks/{task_id}. Right after it is
queued the API may not know it yet, then reports it PENDING until a
worker starts it: both are waited for.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
task_id | str | required | The identifier of the task, as an answer of the API gives it. |
timeout | float | 1800 | Seconds to wait in all. |
interval | float | 2 | Seconds between two reads. |
pending_grace | float | 60 | Seconds during which an unknown task is taken for one not recorded yet. |
on_wait | callable | None | Called with the seconds waited so far, before each pause: shows the progress. |
Returns
dict- The task, ended in success, with its
result.
Raises
TaskFailed- When the task failed or was revoked.
WaitTimeout- When the task is not over after
timeoutseconds.
urllib_transportfunction#
def urllib_transport(timeout: float = 120) -> TransportMake the default transport, built on urllib.request.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
timeout | float | 120 | Seconds to wait for an answer. |
Returns
Transport- A function that sends a request and returns its status and body. An
HTTP error is returned like any answer; only the absence of an answer
raises
ApiUnreachable. A redirection is not followed: it raisesRedirected, with the address the API sends to.

