menuTicketing

Ticketing Python Library

GitHub

Repository

bash

Example

Basic Example

An asyncio-based API. Connect to a single server, acquire a key, and release it right away.

python
broker = TicketBroker.connect("127.0.0.1:5225")
try:
    await broker.wait_ready(5)

    ticket = await broker.acquire("key", wait=5, lease=30)
    await ticket.release()

    print("pass")
finally:
    broker.close()

Concurrency Example (Distributed Lock)

An example that verifies that the balance always returns to its starting value even when several asyncio tasks repeat deposits/withdrawals while mutually excluding each other via a per-account lock. Using async with ticket automatically releases the ticket when the block is exited.

python
async def transaction(broker: TicketBroker, account: int, delta: int) -> None:
    key = f"account-{account}"

    try:
        ticket = await broker.acquire(key, WAIT, LEASE)
    except Exception as e:
        log.error("account %s acquire failed: %s", account, e)
        return

    async with ticket:
        before = BALANCES[account]
        await asyncio.sleep(0)
        after = before + delta
        BALANCES[account] = after

        action, sign = ("withdraw", "-") if delta < 0 else ("deposit", "+")
        log.info("account %s %s %s$%s -> $%s", account, action, sign, AMOUNT, after)

See the full examples in test_example.py, test_bank.py, test_bench.py.