Skip to main content

Broadcaster

Note: This is a fork from encode/brodcaster as it seems not be maintained anymore. See the Changelog for improvements made.

Broadcaster helps you develop realtime streaming functionality by providing a simple broadcast API onto a number of different backend services.

It currently supports Redis PUB/SUB, Redis Streams, Apache Kafka, and Postgres LISTEN/NOTIFY, plus a simple in-memory backend, that you can use for local development or during testing.

WebSockets Demo

Here's a complete example of the backend code for a simple websocket chat app:

app.py

# Requires: `starlette`, `uvicorn`, `jinja2`
# Run with `uvicorn example:app`
import anyio
from broadcaster import Broadcast
from starlette.applications import Starlette
from starlette.routing import Route, WebSocketRoute
from starlette.templating import Jinja2Templates


broadcast = Broadcast("redis://localhost:6379")
templates = Jinja2Templates("templates")


async def homepage(request):
    template = "index.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context)


async def chatroom_ws(websocket):
    await websocket.accept()

    async with anyio.create_task_group() as task_group:
        # run until first is complete
        async def run_chatroom_ws_receiver() -> None:
            await chatroom_ws_receiver(websocket=websocket)
            task_group.cancel_scope.cancel()

        task_group.start_soon(run_chatroom_ws_receiver)
        await chatroom_ws_sender(websocket)


async def chatroom_ws_receiver(websocket):
    async for message in websocket.iter_text():
        await broadcast.publish(channel="chatroom", message=message)


async def chatroom_ws_sender(websocket):
    async with broadcast.subscribe(channel="chatroom") as subscriber:
        async for event in subscriber:
            await websocket.send_text(event.message)


routes = [
    Route("/", homepage),
    WebSocketRoute("/", chatroom_ws, name='chatroom_ws'),
]


app = Starlette(
    routes=routes, on_startup=[broadcast.connect], on_shutdown=[broadcast.disconnect],
)

The HTML template for the front end is available here, and is adapted from Pieter Noordhuis's PUB/SUB demo.

Requirements

Python 3.8+

Installation

  • pip install panthera-broadcaster
  • pip install panthera-broadcaster[redis]
  • pip install panthera-broadcaster[postgres]
  • pip install panthera-broadcaster[kafka]

Available backends

  • Broadcast('memory://')
  • Broadcast("redis://localhost:6379")
  • Broadcast("redis-stream://localhost:6379")
  • Broadcast("postgres://localhost:5432/broadcaster")
  • Broadcast("kafka://localhost:9092")

Using custom backends

You can create your own backend and use it with broadcaster. To do that you need to create a class which extends from BroadcastBackend and pass it to the broadcaster via backend argument.

from broadcaster import Broadcaster, BroadcastBackend

class MyBackend(BroadcastBackend):

broadcaster = Broadcaster(backend=MyBackend())

Where next?

At the moment broadcaster is in Alpha, and should be considered a working design document.

The API should be considered subject to change. If you do want to use Broadcaster in its current state, make sure to strictly pin your requirements to broadcaster==0.3.0.

To be more capable we'd really want to add some additional backends, provide API support for reading recent event history from persistent stores, and provide a serialization/deserialization API...

  • A backend for RabbitMQ.
  • Add support for subscribe('chatroom', history=100) for backends which provide persistence. (Redis Streams, Apache Kafka) This will allow applications to subscribe to channel updates, while also being given an initial window onto the most recent events. We might also want to support some basic paging operations, to allow applications to scan back in the event history.
  • Support for pattern subscribes in backends that support it.

Third Party Packages

MQTT backend

Gist

Integrates MQTT with Broadcaster

Change Log

Version 0.1

  • Forked from encode/brodcaster
  • Fix: ensure backend subscription occurs when adding new subscribers. Previously, if two subscrptions has been made nearly concurrently, only one got events delivered.
  • Feature: allow subscribing to multiple channels
  • Feature: Added serialization / deserialization to support broadcasting structured data.

Metadata

Release files for panthera-broadcaster 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for panthera-broadcaster 0.4.0
File Size Uploaded
panthera_broadcaster-0.4.0.tar.gz 7.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for panthera-broadcaster 0.4.0
File Interpreter ABI Platform
panthera_broadcaster-0.4.0-py3-none-any.whl Python 3 none any Details

Total release size: 17.6 kB

Release files / panthera_broadcaster-0.4.0.tar.gz

Download URL panthera_broadcaster-0.4.0.tar.gz
Size 7.5 kB
Tags Source
SHA-256 checksum
How to use checksums
01c191f989904bd4ef29c990d2d72f15f2b1ad0f3980035dacc1b3f577830b07
BLAKE2b-256 checksum
How to use checksums
a887eb3185134c7e16bc97a14af22ccb23b6a7175ea3625d5c1cdf5986ac3043
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.0.0 CPython/3.10.18

Release files / panthera_broadcaster-0.4.0-py3-none-any.whl

Download URL panthera_broadcaster-0.4.0-py3-none-any.whl
Size 10.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8a55f5b6410e70b59da99626d7a9237c45a24eff2115933d7a03c0c54a696e3f
BLAKE2b-256 checksum
How to use checksums
a4766398accca9d201380249904f347877477af32c3fd05cef660c9910458876
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.0.0 CPython/3.10.18

Release history Release notifications | RSS feed

This release

0.4.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page