Pysher

1.0.8 · maintenance · verified Tue Apr 14

Pysher is a Python module for handling Pusher websockets, based on Erik Kulyk's PythonPusherClient. It provides client-side functionality to connect to Pusher channels, subscribe to events, and bind callbacks to handle real-time data. The project is currently in maintenance mode, welcoming PRs for fixes, updates, and features, with releases occurring periodically for merged improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to Pusher, subscribe to a channel, and bind a callback function to an event. It includes basic logging to observe the connection process and uses environment variables for the Pusher App Key for secure credentials handling.

import pysher
import os
import time
import logging

# Configure logging to see Pysher's internal communication
root = logging.getLogger()
root.setLevel(logging.INFO)
ch = logging.StreamHandler()
root.addHandler(ch)

# Replace with your actual Pusher App Key and Cluster
APP_KEY = os.environ.get('PUSHER_APP_KEY', 'your_app_key')
CLUSTER = os.environ.get('PUSHER_CLUSTER', 'mt1') # e.g., 'mt1', 'eu', 'ap1'

if APP_KEY == 'your_app_key':
    print("WARNING: Please set PUSHER_APP_KEY environment variable or replace 'your_app_key' in the code.")

def my_func(*args, **kwargs):
    """Callback function to process messages from a subscribed event."""
    print(f"Processing Args: {args}")
    print(f"Processing Kwargs: {kwargs}")

def connect_handler(data):
    """Callback function when connection is established."""
    print(f"Connected to Pusher! Connection data: {data}")
    # Subscribe to a channel after successful connection
    channel = pusher.subscribe('my-channel')
    # Bind a callback to a specific event on that channel
    channel.bind('my-event', my_func)
    print("Subscribed to 'my-channel' and bound 'my-event'.")

# Initialize Pusher client
pusher = pysher.Pusher(APP_KEY, cluster=CLUSTER)

# Bind the connect handler to the 'pusher:connection_established' event
pusher.connection.bind('pusher:connection_established', connect_handler)

# Connect to Pusher
print("Connecting to Pusher...")
pusher.connect()

try:
    while True:
        # Keep the main thread alive to allow websocket client to run
        time.sleep(1)
except KeyboardInterrupt:
    print("\nDisconnecting Pysher.")
    pusher.disconnect()
    print("Disconnected.")

view raw JSON →