|
1 | 1 | # Python Async Example |
2 | 2 |
|
3 | | -To get started: |
| 3 | +This example shows how to use Python's `asyncio` with dora nodes. Instead of the |
| 4 | +blocking synchronous API (`for event in node:` or `node.next()`), nodes can use |
| 5 | +`await node.recv_async()` to receive events without blocking the thread — allowing |
| 6 | +other coroutines to run concurrently. |
| 7 | + |
| 8 | +Use the async API when your node needs to integrate with async frameworks (e.g. |
| 9 | +`asyncio`, web servers, async I/O libraries). |
| 10 | + |
| 11 | +## Overview |
| 12 | + |
| 13 | +The [`dataflow.yaml`](./dataflow.yaml) defines two nodes: |
| 14 | + |
| 15 | +- **send_data** — triggered every 10ms by a built-in dora timer, sends the current |
| 16 | + timestamp (nanoseconds, `uint64`) as output `data`. Stops after 100 sends. |
| 17 | +- **receive_data_with_sleep** — receives each timestamp using `await node.recv_async()` |
| 18 | + inside an `asyncio` event loop. Processes 50 events, then prints `done!` and exits. |
| 19 | + |
| 20 | +``` |
| 21 | +dora/timer/millis/10 ──► send_data ──► receive_data_with_sleep |
| 22 | +``` |
| 23 | + |
| 24 | +### Sync vs async API |
| 25 | + |
| 26 | +| | Sync | Async | |
| 27 | +|---|---|---| |
| 28 | +| Receive next event | `for event in node:` or `node.next()` | `await node.recv_async()` | |
| 29 | +| Thread behaviour | Blocks until event arrives | Yields to event loop while waiting | |
| 30 | +| Use when | Simple scripts | Integrating with asyncio / async frameworks | |
| 31 | + |
| 32 | +## Getting started |
| 33 | + |
| 34 | +Install dependencies and build the dataflow: |
4 | 35 |
|
5 | 36 | ```bash |
| 37 | +cd examples/python-async |
6 | 38 | uv venv --seed -p 3.11 |
7 | 39 | uv pip install -e ../../apis/python/node |
8 | 40 | dora build dataflow.yaml --uv |
| 41 | +``` |
| 42 | + |
| 43 | +Run the dataflow: |
| 44 | + |
| 45 | +```bash |
9 | 46 | dora run dataflow.yaml --uv |
10 | 47 | ``` |
| 48 | + |
| 49 | +## Expected output |
| 50 | + |
| 51 | +The `receive_data_with_sleep` node prints a single line after processing 50 events: |
| 52 | + |
| 53 | +``` |
| 54 | +done! |
| 55 | +``` |
| 56 | + |
| 57 | +No output is produced by `send_data` — it sends timestamps silently and exits after |
| 58 | +100 sends. |
0 commit comments