---
metadata:
  - name: generator
    content: Diplodoc Platform v5.70.2
alternate:
  - https://ytsaurus.tech/docs/en/flow/python/examples/url_downloader.md
  - https://ytsaurus.tech/docs/ru/flow/python/examples/url_downloader.md
  - href: https://ytsaurus.tech/docs/en/flow/python/examples/url_downloader.md
    type: text/markdown
    title: Markdown version
  - href: https://ytsaurus.tech/docs/en/llms.txt?revision=4a326afffe920ab6ff3440ff596eb1966933d8bd
    rel: describedby
---
> **Documentation Index:** Fetch the complete configuration index at https://ytsaurus.tech/docs/en/llms.txt?revision=4a326afffe920ab6ff3440ff596eb1966933d8bd

<!-- source: en/_includes/flow/python/examples/url_downloader.md -->
# URL Downloader in YTsaurus Flow (Python)

This example shows a [pipeline](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#pipeline) that groups incoming URLs by host and processes them in batches using [timers](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#timer). It demonstrates the typical pattern: “accumulate in state → process by timer → clear state.”

[Source code](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/python/url_downloader)

## Structure

The pipeline includes a single transform-[computation](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#stream-and-computation) called `url_downloader`, which:

- Accepts messages with `host` and `url` fields from the input [stream](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#stream-and-computation).
- Accumulates URLs for each host in an internal YSON [state](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#state).
- Sets a timer for 5 seconds ahead each time a new URL arrives.
- When the timer fires, it processes all accumulated URLs and publishes the results to the output stream `processed_urls`.

## `url_download_function.py`

This file contains the core processing logic. The function implements both `RowFunction` methods: `on_message` to accumulate URLs in the state and `on_timer` to process them in batches.

```python
class UrlDownloadFunction(RowFunction):
    """Groups URLs by host, processes them with a timer-driven loop."""

    def on_message(self, message, output, ctx):
        host = message.payload["host"]
        url = message.payload["url"]

        state = ctx.state("host-state", message)
        data = state.get_or_default({"host": host, "pending_urls": []})
        data["pending_urls"].append(url)
        state.set(data)

        output.add_timer(int(time.time()) + 5)

    def on_timer(self, timer, output, ctx):
        state = ctx.state("host-state", timer)
        data = state.get_or_default(None)
        if not data or not data.get("pending_urls"):
            state.clear()
            return

        host = data["host"]
        for url in list(data["pending_urls"]):
            result = _process_url(url)
            builder = ctx.message_builder("processed_urls")
            builder.set("host", host)
            builder.set("url", url)
            builder.set("data", result)
            output.add_message(builder.finish())
            log.debug("Processed url (Host: %s, Url: %s)", host, url)

        state.clear()
```

## `__main__.py`

This is the entry point: it creates the pipeline and registers the single `url_downloader` computation.

```python
def main():
    log.info("Starting companion execution")

    pipeline = Pipeline()
    pipeline.add("url_downloader", UrlDownloadFunction())

    log.info("Starting pipeline...")
    pipeline.run()
    log.info("Pipeline completed")
```

## Key patterns

- **Timer-driven batch processing**: `output.add_timer(int(time.time()) + 5)` in `on_message` and the processing logic in `on_timer` provide a standard way to batch events by a time window.
- **Internal YSON state** via `ctx.state("host-state", message)`: the `get_or_default` / `set` / `clear` pattern helps you accumulate and clear data.
- **State key by host**: you group URLs by host using `group_by_schema` in the [spec](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#spec-and-dynamic-spec), so each computation instance processes URLs for a single host in isolation.
- **MessageBuilder**: `ctx.message_builder("processed_urls")` builds output messages with an explicit stream schema.
- **Safety check in `on_timer`**: `if not data or not data.get("pending_urls")` prevents reprocessing data after the state is cleared.
<!-- endsource: en/_includes/flow/python/examples/url_downloader.md -->

<!-- source: en/_includes/flow/python/examples/url_downloader_also.md -->
## See also

- [Quick start (Python)](https://ytsaurus.tech/docs/en/flow/python/getting-started.md)
- [Computation (Python)](https://ytsaurus.tech/docs/en/flow/python/computation.md)
- [Timers](https://ytsaurus.tech/docs/en/flow/concepts/timers.md)
- [Stateful processing](https://ytsaurus.tech/docs/en/flow/concepts/stateful.md)
- [Similar example in C++](https://ytsaurus.tech/docs/en/flow/cpp/examples/url_downloader.md)
- [Similar example in Java](https://ytsaurus.tech/docs/en/flow/java/examples/url_downloader.md)
<!-- endsource: en/_includes/flow/python/examples/url_downloader_also.md -->
