> Complete content index: https://sirannon.sondelali.com/llms.txt

# Python client

> Call registered reads and writes from Python, keep a query result current, and route calls across a replication group with sirannon-client.

URL: https://sirannon.sondelali.com/docs/python-client
Section: Networked access
Version: 0.4 (@delali/sirannon-db@0.4.1, latest)

`sirannon-client` connects a Python 3.11 or later program to a Sirannon server over WebSocket or HTTP. The package contains `SirannonClient` for blocking code and `AsyncSirannonClient` for `asyncio`. Both forms return every integer as a Python `int` and every BLOB as `bytes`, so your program reads a value beyond 2^53 exactly as SQLite stores it.

Build `orders_client.py` step by step against the `server.ts` from [registered operations](/docs/registered-operations), which serves the `orders` database and authenticates every request as the account `u_maria`.

## Install the client

Install the package from PyPI into the environment of your program. The examples on this page use version 0.1.0, and pip installs `httpx`, `pydantic`, `typing-extensions`, and `websockets` with it.

```bash
pip install sirannon-client==0.1.0
```

## Generate the references from the server's operations

The server refuses SQL unless you start it with `acceptSql: true`, so a Python program calls the operations that the server registers. `sirannon-codegen` writes a typed reference for each of them. In the workspace that holds `operations.ts` and `server.ts`, write the references into a `python` folder beside them:

```bash
pnpm exec sirannon-codegen --registry ./operations.ts --python ./python/operations.py
```

The 0.4.1 generator writes this complete file from that registry:

```python title="operations.py"
"""Generated by sirannon-codegen from the operation registry. Do not edit."""

from typing import Any, TypedDict

from sirannon_client import ReadRef, WriteRef

REGISTRY_DIGEST: str | None = "8848da8cd5d9537501dbf824f7bdaf25a64c3fec419376367088c832787c529d"


class OrdersMyOrdersArgs(TypedDict):
    pass


class OrdersMyOrdersRow(TypedDict):
    id: Any
    total: Any
    status: Any


class OrdersOrdersByStatusArgs(TypedDict):
    status: Any


class OrdersOrdersByStatusRow(TypedDict):
    id: Any
    total: Any
    status: Any


class OrdersPlaceOrderArgs(TypedDict):
    total: Any


class OrdersOperations:
    """The registered operations of the "orders" database."""

    class Reads:
        myOrders: ReadRef[OrdersMyOrdersArgs, OrdersMyOrdersRow] = ReadRef("myOrders")
        ordersByStatus: ReadRef[OrdersOrdersByStatusArgs, OrdersOrdersByStatusRow] = ReadRef("ordersByStatus")

    class Writes:
        placeOrder: WriteRef[OrdersPlaceOrderArgs] = WriteRef("placeOrder")
```

Each database becomes a class with nested `Reads` and `Writes` classes. Inside them, each operation becomes a `ReadRef` or a `WriteRef` whose arguments and rows are `TypedDict` types. Every value takes the type `Any`, because the registry declares the names of the arguments and columns without their types. `ownerId` appears in no argument type, since the server fills it from the authenticated identity.

A Python project that has no copy of the server's source can generate the same file from a manifest. Add `--manifest` when you generate the references in the server's workspace, and commit the manifest that the generator writes:

```bash
pnpm exec sirannon-codegen --registry ./operations.ts --python ./python/operations.py --manifest ./operations.json
```

The Python project can then generate its references from that manifest through pnpm, without a Node project:

```bash
pnpm --package=@delali/sirannon-db@0.4.1 dlx sirannon-codegen --from-manifest ./operations.json --python ./operations.py
```

## Read and write through the references

Delete the `data` folder beside `server.ts` and start the server with a secret `SIRANNON_TOKEN`, so that the database holds only the three orders that `server.ts` inserts. Save this complete `orders_client.py` in the `python` folder and execute it with the same `SIRANNON_TOKEN`:

```python title="orders_client.py"
import os

from sirannon_client import SirannonClient

from operations import OrdersOperations

token = os.environ.get("SIRANNON_TOKEN")
if not token:
    raise SystemExit("Set SIRANNON_TOKEN to the application credential")

reads = OrdersOperations.Reads
writes = OrdersOperations.Writes

with SirannonClient("http://127.0.0.1:9876", headers={"Authorization": f"Bearer {token}"}) as client:
    db = client.database("orders")
    print(db.query(reads.ordersByStatus({"status": "pending"})))
    print(db.execute(writes.placeOrder({"total": 2750})))
    print(db.query(reads.myOrders({})))
```

```text result
[{'id': 1, 'total': 4999, 'status': 'pending'}]
[ExecuteResponse(changes=1, last_insert_row_id=4), ExecuteResponse(changes=1, last_insert_row_id=4)]
[{'id': 1, 'total': 4999, 'status': 'pending'}, {'id': 3, 'total': 890, 'status': 'shipped'}, {'id': 4, 'total': 2750, 'status': 'pending'}]
```

The server fills `ownerId` with `u_maria` on every call, so both reads leave out order 2, which `u_ravi` owns. `execute` returns one `ExecuteResponse` for each statement of the write, which gives `placeOrder` one result for its insert and one for its counter update.

When you call a reference with its arguments, as in `reads.ordersByStatus({"status": "pending"})`, mypy checks every key against the operation. A call such as `reads.ordersByStatus({"state": "pending"})` therefore fails `mypy --strict` with a missing `status` key and an extra `state` key. `db.query(reads.ordersByStatus, {"status": "pending"})` sends the same request, although mypy checks only the row type in that form.

The client raises the error of a failed write without sending the write again. When the reply to a write goes missing, the server can still commit the write, so check the orders before your program repeats it.

## Keep the pending orders current

`db.live` opens a [live query](/docs/live-queries) on a registered read and returns once the client holds the first rows. Each time the table changes, the server sends edits to those rows. Once the client applies an edit, in the order in which the server sends them, it calls every listener with a `LiveUpdate`. Delete the `data` folder and start the server again, then execute the extended file:

```python title="orders_client.py"
import os
import threading  # [!code ++]

from sirannon_client import SirannonClient  # [!code --]
from sirannon_client import LiveUpdate, SirannonClient  # [!code ++]

from operations import OrdersOperations  # [!code --]
from operations import OrdersOperations, OrdersOrdersByStatusRow  # [!code ++]

token = os.environ.get("SIRANNON_TOKEN")
if not token:
    raise SystemExit("Set SIRANNON_TOKEN to the application credential")

reads = OrdersOperations.Reads
writes = OrdersOperations.Writes
updated = threading.Event()  # [!code ++:8]


def on_update(update: LiveUpdate[OrdersOrdersByStatusRow]) -> None:
    if update.kind == "ops":
        print("live", [row["id"] for row in update.state.rows])
        updated.set()


with SirannonClient("http://127.0.0.1:9876", headers={"Authorization": f"Bearer {token}"}) as client:
    db = client.database("orders")
    print(db.query(reads.ordersByStatus({"status": "pending"})))
    print(db.execute(writes.placeOrder({"total": 2750})))
    print(db.query(reads.myOrders({})))

    pending = db.live(reads.ordersByStatus({"status": "pending"}))  # [!code ++:7]
    print("live", [row["id"] for row in pending.rows])
    stop_listening = pending.subscribe(on_update)
    db.execute(writes.placeOrder({"total": 6400}))
    updated.wait(timeout=10)
    stop_listening()
    pending.close()
```

```text result
[{'id': 1, 'total': 4999, 'status': 'pending'}]
[ExecuteResponse(changes=1, last_insert_row_id=4), ExecuteResponse(changes=1, last_insert_row_id=4)]
[{'id': 1, 'total': 4999, 'status': 'pending'}, {'id': 3, 'total': 890, 'status': 'shipped'}, {'id': 4, 'total': 2750, 'status': 'pending'}]
live [1, 4]
live [1, 4, 5]
```

`update.kind` holds `rows` for a fresh result, `ops` for edits, `revalidating` while the connection is down, and `error` for a failure, so the listener prints only after an edit. `SirannonClient` calls every listener on a separate delivery thread, which is why the program waits on a `threading.Event` before it closes the query. After a reconnection, the client subscribes again and replaces the rows with a fresh result.

Live queries and table subscriptions need the WebSocket transport, which the client uses unless you pass `transport="http"`. Over HTTP, both fail with `TRANSPORT_ERROR`.

## Handle what the server refuses

The client raises every failure as a `SirannonError`, whose `code`, `message`, `details`, and `status` hold what the server sent. Delete the `data` folder and start the server again, then execute the file with two refused calls at its end:

```python title="orders_client.py"
import os
import threading

from sirannon_client import LiveUpdate, SirannonClient  # [!code --]
from sirannon_client import LiveUpdate, SirannonClient, SirannonError  # [!code ++]

from operations import OrdersOperations, OrdersOrdersByStatusRow

token = os.environ.get("SIRANNON_TOKEN")
if not token:
    raise SystemExit("Set SIRANNON_TOKEN to the application credential")

reads = OrdersOperations.Reads
writes = OrdersOperations.Writes
updated = threading.Event()


def on_update(update: LiveUpdate[OrdersOrdersByStatusRow]) -> None:
    if update.kind == "ops":
        print("live", [row["id"] for row in update.state.rows])
        updated.set()


with SirannonClient("http://127.0.0.1:9876", headers={"Authorization": f"Bearer {token}"}) as client:
    db = client.database("orders")
    print(db.query(reads.ordersByStatus({"status": "pending"})))
    print(db.execute(writes.placeOrder({"total": 2750})))
    print(db.query(reads.myOrders({})))

    pending = db.live(reads.ordersByStatus({"status": "pending"}))
    print("live", [row["id"] for row in pending.rows])
    stop_listening = pending.subscribe(on_update)
    db.execute(writes.placeOrder({"total": 6400}))
    updated.wait(timeout=10)
    stop_listening()
    pending.close()

    try:  # [!code ++:8]
        db.query("SELECT id, total FROM orders")
    except SirannonError as error:
        print(error)
    try:
        db.on("orders").subscribe(print)
    except SirannonError as error:
        print(error)
```

```text result
[{'id': 1, 'total': 4999, 'status': 'pending'}]
[ExecuteResponse(changes=1, last_insert_row_id=4), ExecuteResponse(changes=1, last_insert_row_id=4)]
[{'id': 1, 'total': 4999, 'status': 'pending'}, {'id': 3, 'total': 890, 'status': 'shipped'}, {'id': 4, 'total': 2750, 'status': 'pending'}]
live [1, 4]
live [1, 4, 5]
SQL_NOT_ACCEPTED: This server does not accept SQL over the network. Call a registered operation by name, or start the server with acceptSql: true.
SQL_NOT_ACCEPTED: This server keeps table subscriptions off; subscribe to a registered read by name, or give the server acceptSql: true or an onBeforeSubscribe hook
```

The client refuses the statement itself, because the server's capabilities leave out `query.sql`, so the client sends no request for it. The server refuses the table subscription, since a subscription to a whole table can deliver rows that no registered read returns. A server that you start with `acceptSql: true`, or with an `onBeforeSubscribe` hook that authorises each table and filter, accepts `db.on("orders").filter({"status": "pending"}).subscribe(callback, on_reset=reload)`.

Such a subscription delivers each change once, in the order of the server's change log. While 1024 callbacks wait on the delivery thread, the client pauses reading from the connection until they catch up. After a dropped connection, the client reconnects every `reconnect_interval_ms` and resumes from the last change that it delivered. When the server holds no history after that change, the client calls `on_reset`, so read the table again in that function. [Subscription resumption](/docs/subscription-resumption) describes the cursor that the server keeps.

`ErrorCodes` lists the codes that the client raises when it fails before the server answers, such as `CONNECTION_ERROR`, `TIMEOUT`, and `TRANSPORT_ERROR`. `status` is the HTTP status of the response that contains the error, so it is `None` for both refusals above, because neither of them arrives in an HTTP response. [Error codes](/docs/error-codes) lists the codes that the server sends.

## Call the server from asyncio

Every method of `SirannonClient` blocks until the server answers, while the method of the same name on `AsyncSirannonClient` is a coroutine. Both forms also have a typed method for every route that Sirannon describes in `openapi.json`, such as `get_capabilities` and `get_health`, and each of those methods returns a model of the route's response. Delete the `data` folder and start the server again, then save and execute this complete `orders_async.py` in the `python` folder:

```python title="orders_async.py"
import asyncio
import os

from sirannon_client import AsyncSirannonClient

from operations import OrdersOperations

reads = OrdersOperations.Reads


async def main(token: str) -> None:
    async with AsyncSirannonClient("http://127.0.0.1:9876", headers={"Authorization": f"Bearer {token}"}) as client:
        capabilities = await client.get_capabilities()
        print(capabilities.capabilities)
        db = client.database("orders")
        shipped, pending = await asyncio.gather(
            db.query(reads.ordersByStatus({"status": "shipped"})),
            db.query(reads.ordersByStatus({"status": "pending"})),
        )
        print(shipped)
        print(pending)


token = os.environ.get("SIRANNON_TOKEN")
if not token:
    raise SystemExit("Set SIRANNON_TOKEN to the application credential")
asyncio.run(main(token))
```

```text result
['query.named']
[{'id': 3, 'total': 890, 'status': 'shipped'}]
[{'id': 1, 'total': 4999, 'status': 'pending'}]
```

The server lists `query.named` alone, because it serves registered operations and refuses SQL. The client has no device sync controller, so a Python program that syncs a device calls the device sync routes itself.

## Route calls across a replication group

`TopologyAwareClient` and `AsyncTopologyAwareClient` send writes to the primary of a [replication group](/docs/distributed-replication) and send reads to the node that `read_preference` selects. Save this complete `orders_replicas.py` in the `python` folder, and set `SIRANNON_PRIMARY_URL` and a comma-separated `SIRANNON_REPLICA_URLS` to the addresses of your nodes:

```python title="orders_replicas.py"
import os

from sirannon_client import TopologyAwareClient

from operations import OrdersOperations

token = os.environ.get("SIRANNON_TOKEN")
primary = os.environ.get("SIRANNON_PRIMARY_URL")
replicas = os.environ.get("SIRANNON_REPLICA_URLS")
if not token or not primary or not replicas:
    raise SystemExit("Set SIRANNON_TOKEN, SIRANNON_PRIMARY_URL, and SIRANNON_REPLICA_URLS")

with TopologyAwareClient(
    primary=primary,
    replicas=[url.strip() for url in replicas.split(",")],
    read_preference="replica",
    headers={"Authorization": f"Bearer {token}"},
) as client:
    db = client.database("orders")
    db.execute(OrdersOperations.Writes.placeOrder({"total": 1800}))
    print(db.query(OrdersOperations.Reads.myOrders({})))
```

This example needs a replication group, so it has no fixed result panel. The program prints the orders of `u_maria` from a replica, which can answer before it holds the new order.

`read_preference` takes `primary`, `replica`, or `nearest`, and with `nearest` the client measures the latency of each node. With `discovery="coordinator"` and a list of `endpoints`, the client fetches the group's routing from `GET /db/{id}/cluster` and sends calls to the new primary after a failover. When the client cannot reach the node for a read, it sets that node aside for five seconds and sends the read once more to another node. A write reaches the server twice only when your program sends it twice, because the client raises the error of a failed write without sending it again. [Topology-aware routing](/docs/topology-routing) describes the same routing for the TypeScript client.

## Client options

`SirannonClient` and `AsyncSirannonClient` take the server's address and these keyword arguments.

| Option | Default | Behaviour |
| --- | --- | --- |
| `transport` | `"websocket"` | The client also accepts `"http"`, which serves every call except live queries and subscriptions. |
| `headers` | none | The client sends these headers with every HTTP request and WebSocket handshake. |
| `websocket_protocols` | none | The client offers these subprotocols after `sirannon.v1`. |
| `auto_reconnect` | `True` | The client reconnects after a WebSocket connection drops and restores every subscription. |
| `reconnect_interval_ms` | `1000` | The client waits this many milliseconds between reconnection tries. |
| `request_timeout_ms` | `30000` | The client waits this many milliseconds for each answer, and with `0` it waits without a limit. |
| `max_response_bytes` | 64 MiB | The client refuses a larger answer, and with `0` it accepts any size. |
| `http_client` | none | `SirannonClient` sends its route calls through this `httpx.Client`, which your program closes. |

`TopologyAwareClient` takes the same transport settings, together with `primary`, `replicas`, `endpoints`, `read_preference`, `discovery`, and `read_concern`. When the server closes a WebSocket connection with `4401` or `4403`, the client raises `UNAUTHORIZED` or `FORBIDDEN` and stops reconnecting, because the same credential fails every later try. The [Go client](/docs/go-client) offers the same calls and routing.
