Databases python Advanced

Redis Pub/Sub Listener

Subscribe to a Redis channel and dispatch messages to registered handlers.

python
import redis, json, threading

r = redis.from_url("redis://localhost:6379/0")

def listen(channel: str, handlers: dict):
    ps = r.pubsub()
    ps.subscribe(channel)
    def _run():
        for msg in ps.listen():
            if msg["type"] != "message": continue
            data = json.loads(msg["data"])
            fn = handlers.get(data.get("event"))
            if fn: fn(data)
    threading.Thread(target=_run, daemon=True).start()

listen("events", {"module.published": lambda d: print("New module:", d)})

Prerequisites

  • redis-py >= 4

Pro Tips

  • → Use asyncio + aioredis for async frameworks.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
python
Level
Advanced
Read time
4 min
Published
Jan 2026
License
Commercial License

Newsletter

New modules every week, directly to your inbox.