Pusher Python Library

3.3.4 · active · verified Fri Apr 10

The `pusher` Python library (current version 3.3.4) provides an interface to interact with the Pusher Channels HTTP API. It enables developers to trigger events to clients, query channel states, validate webhooks, and authenticate private or presence channels. The library is actively maintained with regular updates.

Warnings

Install

Imports

Quickstart

Initializes the Pusher client using application credentials (preferably from environment variables) and demonstrates how to trigger an event to a channel and how to authenticate a private or presence channel subscription for a client.

import os
from pusher import Pusher

# Configure Pusher client with environment variables
pusher_client = Pusher(
    app_id=os.environ.get('PUSHER_APP_ID', 'YOUR_APP_ID'),
    key=os.environ.get('PUSHER_APP_KEY', 'YOUR_APP_KEY'),
    secret=os.environ.get('PUSHER_APP_SECRET', 'YOUR_APP_SECRET'),
    cluster=os.environ.get('PUSHER_APP_CLUSTER', 'us2'), # e.g., 'us2', 'eu', 'ap2'
    ssl=True
)

# --- Example 1: Triggering an event ---
try:
    response = pusher_client.trigger(
        'my-channel',
        'my-event',
        {'message': 'hello world'}
    )
    print(f"Event triggered successfully: {response}")
except Exception as e:
    print(f"Error triggering event: {e}")

# --- Example 2: Authenticating a channel subscription (server-side) ---
# This typically happens in a web endpoint receiving a POST request
# from a client, containing socket_id and channel_name.

socket_id = "123.456" # Example socket_id from client
channel_name = "private-my-channel" # Example channel name
user_id = "user-123" # Required for presence channels
user_info = {"name": "John Doe"} # Optional, for presence channels

try:
    auth_response = pusher_client.authenticate(
        channel=channel_name,
        socket_id=socket_id,
        custom_data={'user_id': user_id, 'user_info': user_info} # Use custom_data for user-specific info
    )
    print(f"Authentication response for {channel_name}: {auth_response}")
except Exception as e:
    print(f"Error authenticating {channel_name}: {e}")

view raw JSON →