Skip to content

Async apps

Machyon is asynchronous inside. If your code already runs an event loop, use the awaitable API and Machyon shares it.

In Jupyter

Notebooks run an event loop, so machyon.download() refuses to start (it would block the loop). Await instead:

report = await machyon.adownload("urls.csv", "images/")
report

In your own async code

async_app.py
import machyon


async def main() -> None:
    async with machyon.Downloader("images/", max_retries=8) as dl:
        report = await dl.download("urls.csv", names="{host}/{hash}{ext}")
        print(report)
        for failure in dl.failures:        # what is still missing, and why
            print(failure["reason"], failure["url"], "->", failure["name"])


machyon.run(main())   # asyncio.run(), on uvloop/winloop when installed

Downloader holds an HTTP connection pool, a set of file-writer threads and the adaptive limiter. Reuse one for several download() calls to the same kind of server, and close it when you're done (async with does that).

machyon.run() is asyncio.run() on the fastest event loop installed (uvloop or winloop with the [fast] extra, the standard loop otherwise). Inside an app that manages its own loop, just await Machyon's coroutines.

Several downloads at once

Separate Downloaders are independent: each has its own folder, settings, limiter and ledger.

async_many.py
import asyncio

import machyon


async def main() -> None:
    # Two independent downloads in the same event loop, each with its own folder and settings.
    train, test = await asyncio.gather(
        machyon.adownload("train.csv", "images/train", names="{index}{ext}"),
        machyon.adownload("test.csv", "images/test", names="{index}{ext}", max_concurrency=64),
    )
    print("train:", train)
    print("test: ", test)


asyncio.run(main())

Keep one Downloader per save folder at a time within a process. (Separate processes can share a folder: resuming.)

In a web server

A request handler shouldn't wait for a long download. Start it as a background task and report on it later:

from fastapi import BackgroundTasks, FastAPI

import machyon

app = FastAPI()


async def fetch(job_id: str, urls: list[str]) -> None:
    report = await machyon.adownload(urls, f"jobs/{job_id}", progress=False)
    ...  # store report.to_dict() where your app can find it


@app.post("/jobs/{job_id}")
async def start(job_id: str, urls: list[str], tasks: BackgroundTasks):
    tasks.add_task(fetch, job_id, urls)
    return {"accepted": len(urls)}

Turn the progress bar off (progress=False) wherever nobody watches a terminal.

Cancellation

Cancelling the task that runs a download (or pressing Ctrl+C) stops it cleanly: unfinished rows of the current shard are recorded as interrupted, partial files are removed and the ledger is written before the cancellation propagates. Calling the same download again resumes it. Resuming

Logging

Machyon logs through the standard logging module under the machyon logger, so it fits whatever logging your app already has. machyon.setup_logging(log_dir) adds a console handler and, optionally, a rotating file.