# Python

Source: https://tiltas.openpanel.sh/docs/sdks/python

> pip install tiltas puts one Python program on your Network, with sockets, urlopen and WhoIs.

The Python package wraps [libtiltas](/docs/sdks/c) with `ctypes`, so it has no dependencies and no compiler step. The
wheel carries the library for its platform.

## Install

```sh
pip install tiltas
```

Python 3.9 or newer, on Linux x64 and arm64 (glibc 2.34 or newer: Ubuntu 22.04, Debian 12, RHEL 9), macOS 12 or newer
(Apple silicon and Intel) and Windows x64.

<Component type="warn" title="Beta: not published yet">
Until `tiltas` is on PyPI, build the wheel from a copy of the Tiltas repository (Go 1.27.4, a C compiler and the
`build` package):

```sh
python3 -m pip install build
sdk/c/build.sh
sdk/python/build.sh "$(go env GOOS)/$(go env GOARCH)"
python3 -m pip install sdk/python/dist/tiltas-0.1.0-*.whl
```
</Component>

## Use

```python
import tiltas

with tiltas.Server(name="billing-api") as server:  # the Join key comes from TILTAS_JOIN_KEY
    with server.urlopen("http://ledger/") as res:   # the Service named ledger
        print(res.read().decode())
```

The `with` block joins the Network and, when it ends, leaves it. The complete server and client are in the
[quickstart](/docs/sdks/quickstart).

## API

### class Server

```python
tiltas.Server(name=None, *, panel=None, join_key_file=None, persistent=False, dir=None, verbose=False)
```

| Argument | Default |
|---|---|
| `name` | `TILTAS_NAME`, else the host name. The Panel makes it unique. |
| `panel` | `TILTAS_PANEL`, else `https://tiltas.openpanel.sh`. |
| `join_key_file` | `TILTAS_JOIN_KEY`, else the file in `TILTAS_JOIN_KEY_FILE`. |
| `persistent` | `False`: an ephemeral Device that leaves on `close()`. `True` keeps it across restarts; needs `dir`. |
| `dir` | The state directory of a persistent Server, mode 0700. |
| `verbose` | `False`. `True` writes the network engine's logs to stderr, secrets removed. |

| Method | What it does |
|---|---|
| `up(timeout=60.0)` | Joins on the first start and connects; returns once this program is a Device. Raises `TiltasError`. `with` calls it. |
| `close()` | Disconnects. An ephemeral Device leaves the Network. `with` calls it. |
| `listen(port, backlog=128)` | Returns a listening `socket.socket` that receives the connections to `port` on the Network. |
| `dial(host, port, timeout=30.0)` | Returns a `socket.socket` connected over the Network to a Device or Service by name (short or full) or address. |
| `urlopen(url, data=None, timeout=30.0)` | `urllib.request.urlopen` over the Network: `http://` and `https://`, environment proxies ignored. |
| `whois(addr)` | The `Identity` behind a connection from a socket of `listen`: pass its peer address, as `client_address` or `request.client` give it. |
| `device_id`, `domain`, `addresses` | This Device's id (`dev_…`), the Network's domain, and this Device's addresses. |

### class Identity

A frozen dataclass: `device_id` (`dev_…` for Servers, empty for Personal devices), `name`, `dns_name`, `kind`
(`"server"` or `"personal"`), `addresses`, `tags`, and for Personal devices `member_email` and `member_name`.

### TiltasError

Raised for a missing or refused Join key, an unreachable Panel, a Device allowance that is full, and a `whois` for an
address that did not come in over the Network. Its message never contains a key.

## How listen works

`listen(80)` binds a socket to a free port on `127.0.0.1` and has the library forward every connection to the
Network's port 80 to it. Hand the socket to any server: `http.server` (as in the quickstart),
`uvicorn.Server(config).run(sockets=[sock])`, or your own `accept()` loop.

The peer address your server sees is the library's end of the forward. `whois` maps it back to the Device that called.
Other programs on the same computer can also connect to that loopback port; `whois` refuses them, so check every
caller with it, as the examples do.

## FastAPI

```python title="examples/python/fastapi_app.py"
"""A FastAPI app served only on a Tiltas Network.

    pip install fastapi uvicorn
    TILTAS_JOIN_KEY=qlj_… TILTAS_NAME=hello-server python fastapi_app.py
"""

import uvicorn
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import PlainTextResponse

import tiltas

app = FastAPI()
server = tiltas.Server()

@app.get("/", response_class=PlainTextResponse)
def hello(request: Request) -> str:
    try:
        who = server.whois(request.client)
    except tiltas.TiltasError:
        raise HTTPException(403, "unknown caller")
    return f"hello {who.name}\n"

if __name__ == "__main__":
    with server:
        sock = server.listen(80)
        print(f"serving on the Network only, as Device {server.device_id}", flush=True)
        # uvicorn stops on SIGTERM and Ctrl-C; then the Device leaves the Network.
        uvicorn.Server(uvicorn.Config(app, log_level="warning")).run(sockets=[sock])
```

`whois` blocks for a moment, so call it from a plain `def` endpoint, which FastAPI runs in a thread, as here.

## Ephemeral or persistent

An ephemeral Server (the default) joins on every start and leaves on `close()`. Handle `SIGTERM` so that `docker stop`
and process managers close it too: the quickstart server does with one line; uvicorn does it for you.

```python
server = tiltas.Server(name="nas-backup", persistent=True, dir="/var/lib/nas-backup/tiltas")
```

A persistent Server joins once and reuses its Device from `dir` on later starts.

## Processes

Each `Server` runs the network inside its process. Create it after any `fork()`: a server that forks workers
(gunicorn, `multiprocessing` with fork) needs a `Server` in each worker, and each worker is then a Device of its own.
