Pusher Python Library
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
- breaking Python 2.x support has been removed, starting from v3.3.3 (tests removed) and implicitly earlier with Python 3.6+ requirement. Users on Python 2.x should use an older version of the library or migrate to Python 3.
- breaking The library no longer supports Push Notifications directly. Support for this feature was removed in v3.0.0. For Push Notifications (Pusher Beams), use the separate `pusher-push-notifications` library.
- deprecated The `encryption_master_key` option in the `Pusher` constructor has been deprecated in favor of `encryption_master_key_base64`.
- gotcha While the library's internal event payload size limit was increased in v3.3.1, the Pusher Channels API still enforces a 10KB size limit per event payload. Exceeding this will result in an API error.
- gotcha The `pusher` library is for server-side interaction (triggering events, authenticating channels). For client-side WebSocket connections to receive events, you typically need a client-side JavaScript library or a separate Python WebSocket client library like `pysher` (or `pusherclient` for older Python client implementations).
Install
-
pip install pusher
Imports
- Pusher
from pusher import Pusher
- PusherClient
from pusher import Pusher
Quickstart
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}")