Skip to main content

Lightweight Python publish/subscribe event bus

Project description

Micro framework for pub/sub decoupling with concurrency support.





Getting Started

0. Install

pip install msg-relay

1. Define Event types and their properties

from relay import Event

@dataclass(frozen=True)
class NewUserCreated(Event):
    user_id: str


@dataclass(frozen=True)
class UserDeleted(Event):
    user_id: str

2. Define Subscribers/Handlers and mapping to event types

from relay import Subscriber

class UserCacheHandler(Subscriber):
    def on_new_user(event: NewUserCreated):
        print(f"Publish user to Cache: {event.user_id}")

    def on_user_deleted(event: UserDeleted):
        print(f"Delete user from Cache: {event.user_id}")

    handlers = {
        NewUserCreated: on_new_user,
        UserDeleted: on_user_deleted,
    }


class EmailHandler(Subscriber):
    def on_new_user(event: NewUserCreated):
        time.sleep(10)
        print(f"Sending welcome email to: {event.user_id}")

    handlers = {
        NewUserCreated: on_new_user,
    }

3. Define Channels

from relay import Channel

user_updates_channel = Channel(
    identifier="user_updates",
    supported_events=[NewUserCreated, UserDeleted],
    executor=ProcessingExecutor.MULTIPLE_THREADS
)

# register subscribers
user_updates_channel.subscribe(EmailHandler())
user_updates_channel.subscribe(UserCacheHandler())

4. Publish events

from relay import publish

# generate events
event2 = NewUserCreated(user_id="21")
event = UserDeleted(user_id="21")

# publish events with channel
user_updates_channel.publish(event)

# or publish events via msgrelay.publish
publish(event2, channel_id="user_updates")

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

msg-relay-0.0.1.tar.gz (4.3 kB view details)

Uploaded Source

File details

Details for the file msg-relay-0.0.1.tar.gz.

File metadata

  • Download URL: msg-relay-0.0.1.tar.gz
  • Upload date:
  • Size: 4.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.8.5

File hashes

Hashes for msg-relay-0.0.1.tar.gz
Algorithm Hash digest
SHA256 f064f29d0226f8abd9d5ba9357afea05da60ae33080a87a25a3318f2ae10bee1
MD5 4f21fe0eae19696a498f05d9e1dc75ef
BLAKE2b-256 1a014be6560521602dbb76ae478398dbd02ba614db9c2d8f8a18c51d3ad74b18

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page