Valkey: Using Pub/Sub with Valkey and Python

This documentation is part of the Using with Python guide. You can view the complete guide here: How to connect Valkey with Python.

👋 Welcome to the Stackhero documentation!

Stackhero offers a ready-to-use Valkey cloud solution that provides a host of benefits, including:

  • Redis Commander web UI included.
  • Unlimited message size and transfers.
  • Effortless updates with just a click.
  • Optimal performance and robust security powered by a private and dedicated VM.

Save time and simplify your life: it only takes 5 minutes to try Stackhero's Valkey cloud hosting solution!

Leveraging the Publish/Subscribe (Pub/Sub) functionality in Python with Valkey is straightforward. Here is an example:

import redis

# Connect to Valkey
r = redis.from_url(
  'rediss://default:<password>@<XXXXXX>.stackhero-network.com:<PORT_TLS>',
  health_check_interval=10,
  socket_connect_timeout=5,
  socket_keepalive=True,
  retry_on_timeout=True
)

# Create a PubSub instance
p = r.pubsub()

# Subscribe to the channel "test"
p.subscribe('test')

# Publish a message to the channel "test"
r.publish('test', 'This is a test message')

# Get the first available message from channel "test"
p.get_message()

# Unsubscribe from channel "test"
p.unsubscribe('test')

Expand your Pub/Sub capabilities with these advanced examples:

# Create a PubSub instance and ignore subscribe messages
p = r.pubsub(ignore_subscribe_messages=True)

# Subscribe to multiple channels
p.subscribe('test-1', 'test-2', ...)

# Unsubscribe from multiple channels
p.unsubscribe('test-1', 'test-2', ...)

# You can also use "unsubscribe" with no arguments, to disconnect from all subscribed channels
p.unsubscribe()

# Subscribe to channels using a pattern
p.psubscribe('my-*')

# Unsubscribe from channels using a pattern
p.punsubscribe('my-*')