• Stars
    star
    368
  • Rank 111,806 (Top 3 %)
  • Language
    Python
  • License
    MIT License
  • Created about 14 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Pusher Channels HTTP API library for Python

Pusher Channels HTTP Python Library

Build Status PyPI version

This package lets you trigger events to your client and query the state of your channels. When used with a server, you can validate webhooks and authenticate private- or presence- channels.

In order to use this library, you need to have a free account on http://pusher.com. After registering, you will need the application credentials for your app.

Supported Platforms

  • Python - supports Python versions 2.7, 3.6 and above

Features

  • Adapters for various http libraries like requests, urlfetch, aiohttp (requires Python >= 3.5.3) and tornado.
  • WebHook validation
  • Signature generation for socket subscriptions

Table of Contents

Installation

You can install this module using your package management method or choice, normally easy_install or pip. For example:

pip install pusher

Users on Python 2.x and older versions of pip may get a warning, due to pip compiling the optional pusher.aiohttp module, which uses Python 3 syntax. However, as pusher.aiohttp is not used by default, this does not affect the library's functionality. See our Github issue, as well as this issue from Gunicorn for more details.

On Linux, you must ensure that OpenSSL is installed, e.g. on Debian/Ubuntu:

$ sudo apt-get install build-essential libssl-dev libffi-dev

Getting started

The minimum configuration required to use the Pusher object are the three constructor arguments which identify your Pusher Channels app. You can find them by going to "API Keys" on your app at https://app.pusher.com.

import pusher
pusher_client = pusher.Pusher(app_id=u'4', key=u'key', secret=u'secret', cluster=u'cluster')

You can then trigger events to channels. Channel and event names may only contain alphanumeric characters, - and _:

pusher_client.trigger(u'a_channel', u'an_event', {u'some': u'data'})

Configuration

import pusher
pusher_client = pusher.Pusher(app_id, key, secret, cluster=u'cluster')
Argument Description
app_id String Required
The Pusher Channels application ID
key String Required
The Pusher Channels application key
secret String Required
The Pusher Channels application secret token
cluster String Default:mt1
The pusher application cluster. Will be overwritten if host is set
host String Default:None
The host to connect to
port int Default:None
Which port to connect to
ssl bool Default:True
Use HTTPS
encryption_master_key String Default:None
Deprecated, see encryption_master_key_base64
encryption_master_key_base64 String Default:None
The encryption master key for End-to-end Encryption
backend Object an object that responds to the send_request(request) method. If none is provided, a pusher.requests.RequestsBackend instance is created.
json_encoder Object Default: None
Custom JSON encoder.
json_decoder Object Default: None
Custom JSON decoder.

The constructor will throw a TypeError if it is called with parameters that donโ€™t match the types listed above.

Example
import pusher
pusher_client = pusher.Pusher(app_id=u'4', key=u'key', secret=u'secret', ssl=True, cluster=u'cluster')

Triggering Events

To trigger an event on one or more channels, use the trigger method on the Pusher object.

Pusher::trigger

Argument Description
channels String or Collection Required
The name or list of names of the channel you wish to trigger events on
event String Required
The name of the event you wish to trigger.
data JSONable data Required
The event's payload
socket_id String Default:None
The socket_id of the connection you wish to exclude from receiving the event. You can read more here.
Return Values Description
buffered_events Dict A parsed response that includes the event_id for each event published to a channel. See example.

Pusher::trigger will throw a TypeError if called with parameters of the wrong type; or a ValueError if called on more than 100 channels, with an event name longer than 200 characters, or with more than 10240 characters of data (post JSON serialisation).

Example

This call will trigger to 'a_channel' and 'another_channel', and exclude the recipient with socket_id "1234.12".

pusher_client.trigger([u'a_channel', u'another_channel'], u'an_event', {u'some': u'data'}, "1234.12")

Pusher::trigger_batch

It's also possible to send distinct messages in batches to limit the overhead of HTTP headers. There is a current limit of 10 events per batch on our multi-tenant clusters.

Argument Description
batch Array of Dict Required
A list of events to trigger

Events are a Dict with keys:

Argument Description
channel String Required
The name of the channel to publish to.
name String Required
The name of the event you wish to trigger.
data JSONable data Required
The event's payload
socket_id String Default:None
The socket_id of the connection you wish to exclude from receiving the event. You can read more here.
Return Values Description
Dict An empty dict on success

Pusher::trigger_batch will throw a TypeError if the data parameter is not JSONable.

Example
pusher_client.trigger_batch([
  { u'channel': u'a_channel', u'name': u'an_event', u'data': {u'some': u'data'}, u'socket_id': '1234.12'},
  { u'channel': u'a_channel', u'name': u'an_event', u'data': {u'some': u'other data'}}
])

Querying Application State

Getting Information For All Channels

Pusher::channels_info

Argument Description
prefix_filter String Default: None
Filter the channels returned by their prefix
attributes Collection Default: []
A collection of attributes which should be returned for each channel. If empty, an empty dictionary of attributes will be returned for each channel.
Available attributes: "user_count".
Return Values Description
channels Dict A parsed response from the HTTP API. See example.

Pusher::channels_info will throw a TypeError if prefix_filter is not a String.

Example
channels = pusher_client.channels_info(u"presence-", [u'user_count'])

#=> {u'channels': {u'presence-chatroom': {u'user_count': 2}, u'presence-notifications': {u'user_count': 1}}}

Getting Information For A Specific Channel

Pusher::channel_info

Argument Description
channel String Required
The name of the channel you wish to query
attributes Collection Default: []
A collection of attributes to be returned for the channel.

Available attributes:
"user_count" : Number of distinct users currently subscribed. Applicable only to presence channels.
"subscription_count": Number of connections currently subscribed to the channel. Enable this feature in your Pusher dashboard's App Settings.
Return Values Description
channel Dict A parsed response from the HTTP API. See example.

Pusher::channel_info will throw a ValueError if channel is not a valid channel.

Example
channel = pusher_client.channel_info(u'presence-chatroom', [u"user_count"])
#=> {u'user_count': 42, u'occupied': True}

Getting User Information For A Presence Channel

Pusher::users_info

Argument Description
channel String Required
The name of the presence channel you wish to query
Return Values Description
users Dict A parsed response from the HTTP API. See example.

Pusher::users_info will throw a ValueError if channel is not a valid channel.

Example
pusher_client.users_info(u'presence-chatroom')
#=> {u'users': [{u'id': u'1035'}, {u'id': u'4821'}]}

Authenticating Channel Subscription

Pusher::authenticate

In order for users to subscribe to a private- or presence-channel, they must be authenticated by your server.

The client will make a POST request to an endpoint (either "/pusher/auth" or any which you specify) with a body consisting of the channel's name and socket_id.

Using your Pusher instance, with which you initialized Pusher, you can generate an authentication signature. Having responded to the request with this signature, the subscription will be authenticated.

Argument Description
channel String Required
The name of the channel, sent to you in the POST request
socket_id String Required
The channel's socket_id, also sent to you in the POST request
custom_data Dict Required for presence channels
This will be a dictionary containing the data you want associated with a member of a presence channel. A "user_id" key is required, and you can optionally pass in a "user_info" key. See the example below.
Return Values Description
response Dict A dictionary to send as a response to the authentication request.

Pusher::authenticate will throw a ValueError if the channel or socket_id that itโ€™s called with are invalid.

Example
Private Channels
auth = pusher_client.authenticate(

  channel=u"private-channel",

  socket_id=u"1234.12"
)
# return `auth` as a response
Presence Channels
auth = pusher_client.authenticate(

  channel=u"presence-channel",

  socket_id=u"1234.12",

  custom_data={
    u'user_id': u'1',
    u'user_info': {
      u'twitter': '@pusher'
    }
  }
)
# return `auth` as a response

Terminating user connections

TIn order to terminate a user's connections, the user must have been authenticated. Check the Server user authentication docs for the information on how to create a user authentication endpoint.

To terminate all connections established by a given user, you can use the terminate_user_connections function:

pusher_client.terminate_user_connections(userId)

Please note, that it only terminates the user's active connections. This means, if nothing else is done, the user will be able to reconnect. For more information see: Terminating user connections docs.

End to End Encryption

This library supports end to end encryption of your private channels. This means that only you and your connected clients will be able to read your messages. Pusher cannot decrypt them. You can enable this feature by following these steps:

  1. You should first set up Private channels. This involves creating an authentication endpoint on your server.

  2. Next, generate a 32 byte master encryption key, base64 encode it and store it securely.

    This is secret and you should never share this with anyone. Not even Pusher.

    To generate a suitable key from a secure random source, you could use:

    openssl rand -base64 32
  3. Pass your master key to the SDK constructor

    import pusher
    
    pusher_client = pusher.Pusher(
      app_id='yourappid',
      key='yourkey',
      secret='yoursecret',
      encryption_master_key_base64='<output from command above>',
      cluster='yourclustername',
      ssl=True
    )
    
    pusher_client.trigger('private-encrypted-my-channel', 'my-event', {
      'message': 'hello world'
    })
  4. Channels where you wish to use end to end encryption must be prefixed with private-encrypted-.

  5. Subscribe to these channels in your client, and you're done! You can verify it is working by checking out the debug console on the https://dashboard.pusher.com/ and seeing the scrambled ciphertext.

Important note: This will not encrypt messages on channels that are not prefixed by private-encrypted-.

More info on End-to-end Encrypted Channels here.

Receiving Webhooks

If you have webhooks set up to POST a payload to a specified endpoint, you may wish to validate that these are actually from Pusher. The Pusher object achieves this by checking the authentication signature in the request body using your application credentials.

Pusher::validate_webhook

Argument Description
key String Required
Pass in the value sent in the request headers under the key "X-PUSHER-KEY". The method will check this matches your app key.
signature String Required
This is the value in the request headers under the key "X-PUSHER-SIGNATURE". The method will verify that this is the result of signing the request body against your app secret.
body String Required
The JSON string of the request body received.
Return Values Description
body_data Dict If validation was successful, the return value will be the parsed payload. Otherwise, it will be None.

Pusher::validate_webhook will raise a TypeError if it is called with any parameters of the wrong type.

Example
webhook = pusher_client.validate_webhook(

  key="key_sent_in_header",

  signature="signature_sent_in_header",

  body="{ \"time_ms\": 1327078148132  \"events\": [ { \"name\": \"event_name\", \"some\": \"data\" }  ]}"
)

print webhook["events"]

Request Library Configuration

Users can configure the library to use different backends to send calls to our API. The HTTP libraries we support are:

  • Requests (pusher.requests.RequestsBackend). This is used by default.
  • Tornado (pusher.tornado.TornadoBackend).
  • AsyncIO (pusher.aiohttp.AsyncIOBackend).
  • Google App Engine (pusher.gae.GAEBackend).

Upon initializing a Pusher instance, pass in any of these options to the backend keyword argument.

Google App Engine

GAE users are advised to use the pusher.gae.GAEBackend backend to ensure compatability.

Feature Support

Feature Supported
Trigger event on single channel โœ”
Trigger event on multiple channels โœ”
Excluding recipients from events โœ”
Authenticating private channels โœ”
Authenticating presence channels โœ”
Get the list of channels in an application โœ”
Get the state of a single channel โœ”
Get a list of users in a presence channel โœ”
WebHook validation โœ”
Terminate user connections โœ”
Heroku add-on support โœ”
Debugging & Logging โœ”
Cluster configuration โœ”
Timeouts โœ”
HTTPS โœ”
End-to-end Encryption โœ”
HTTP Proxy configuration โœ˜
HTTP KeepAlive โœ˜

Helper Functionality

These are helpers that have been implemented to to ensure interactions with the HTTP API only occur if they will not be rejected e.g. channel naming conventions.

Helper Functionality Supported
Channel name validation โœ”
Limit to 100 channels per trigger โœ”
Limit event name length to 200 chars โœ”

Running the tests

To run the tests run python setup.py test

License

Copyright (c) 2015 Pusher Ltd. See LICENSE for details.

More Repositories

1

pusher-js

Pusher Javascript library
JavaScript
1,970
star
2

atom-pair

An Atom package that allows for epic pair programming
JavaScript
1,454
star
3

pusher-http-php

PHP library for interacting with the Pusher Channels HTTP API
PHP
1,355
star
4

pusher-http-ruby

Ruby library for Pusher Channels HTTP API
Ruby
659
star
5

libPusher

An Objective-C interface to Pusher Channels
C
409
star
6

pusher-http-laravel

[DEPRECATED] A Pusher Channels bridge for Laravel
PHP
405
star
7

k8s-spot-rescheduler

Tries to move K8s Pods from on-demand to spot instances
Go
311
star
8

pusher-websocket-java

Pusher Channels client library for Java targeting general Java and Android
Java
302
star
9

pusher-websocket-swift

Pusher Channels websocket library for Swift
Swift
267
star
10

build-a-slack-clone-with-react-and-pusher-chatkit

In this tutorial, you'll learn how to build a chat app with React, complete with typing indicators, online status, and more.
JavaScript
235
star
11

pusher-angular

Pusher Angular Library | owner=@leesio
JavaScript
233
star
12

pusher-http-go

Pusher Channels HTTP API library for Go
Go
196
star
13

k8s-spot-termination-handler

Monitors AWS for spot termination notices when run on spot instances and shuts down gracefully
Makefile
118
star
14

NWWebSocket

A WebSocket client written in Swift, using the Network framework from Apple.
Swift
112
star
15

go-interface-fuzzer

Automate the boilerplate of fuzz testing Go interfaces | owner: @willsewell
Go
110
star
16

pusher-http-dotnet

.NET library for interacting with the Pusher HTTP API
C#
109
star
17

k8s-auth-example

Example Kubernetes Authentication helper. Performs OIDC login and configures Kubectl appropriately.
Go
108
star
18

pusher-websocket-dotnet

Pusher Channels Client Library for .NET
C#
107
star
19

faros

Faros is a CRD based GitOps controller
Go
100
star
20

backbone-todo-app

JavaScript
92
star
21

chatkit-client-js

JavaScript client SDK for Pusher Chatkit
JavaScript
89
star
22

quack

In-Cluster templating for Kubernetes manifests
Go
70
star
23

pusher-channels-flutter

Pusher Channels client library for Flutter targeting IOS, Android, and WEB
Dart
67
star
24

websockets-from-scratch-tutorial

Tutorial that shows how to implement a websocket server using Ruby's built-in libs
Ruby
60
star
25

backpusher

JavaScript
54
star
26

push-notifications-php

Pusher Beams PHP Server SDK
PHP
54
star
27

chatkit-android

Android client SDK for Pusher Chatkit
Kotlin
54
star
28

pusher-websocket-react-native

React Native official Pusher SDK
TypeScript
53
star
29

django-pusherable

Real time notification when an object view is accessed via Pusher
Python
52
star
30

notify

Ruby
51
star
31

cli

A CLI for Pusher (beta)
Go
50
star
32

k8s-spot-price-monitor

Monitors the spot prices of instances in a Kubernetes cluster and exposes them as prometheus metrics
Python
44
star
33

chatkit-command-line-chat

A CLI chat, built with Chatkit
JavaScript
41
star
34

pusher-http-java

Java client to interact with the Pusher HTTP API
Java
40
star
35

chatkit-swift

Swift SDK for Pusher Chatkit
Swift
40
star
36

electron-desktop-chat

A desktop chat built with React, React Desktop and Electron
JavaScript
39
star
37

push-notifications-web

Beams Browser notifications
JavaScript
38
star
38

crank

Process slow restarter
Go
37
star
39

pusher-websocket-android

Library built on top of pusher-websocket-java for Android. Want Push Notifications? Check out Pusher Beams!
Java
35
star
40

chameleon

A collection of front-end UI components used across Pusher โœจ
CSS
35
star
41

chatkit-server-php

PHP SDK for Pusher Chatkit
PHP
35
star
42

cide

Isolated test runner with Docker
Ruby
33
star
43

push-notifications-swift

Swift SDK for the Pusher Beams product:
Swift
33
star
44

pusher-phonegap-android

JavaScript
30
star
45

push-notifications-python

Pusher Beams Python Server SDK
Python
30
star
46

pusher-websocket-unity

Pusher Channels Unity Client Library
C#
27
star
47

hacktoberfest

24
star
48

laravel-chat

PHP
22
star
49

push-notifications-android

Android SDK for Pusher Beams
Kotlin
21
star
50

push-notifications-node

Pusher Beams Node.js Server SDK
JavaScript
20
star
51

pusher-test-iOS

iOS app for developers to test connections to Pusher
Objective-C
19
star
52

push-notifications-ruby

Pusher Beams Ruby Server SDK
Ruby
19
star
53

chatkit-server-node

Node.js SDK for Pusher Chatkit
TypeScript
16
star
54

rack-headers_filter

Remove untrusted headers from Rack requests | owner=@zimbatm
Ruby
15
star
55

pusher-test-android

Test and diagnostic app for Android, based on pusher-java-client
Java
14
star
56

pusher-realtime-tfl-cameras

Realtime TfL Traffic Camera API, powered by Pusher
JavaScript
14
star
57

buddha

Buddha command execution and health checking | owner: @willsewell
Go
14
star
58

chatkit-server-go

Chatkit server SDK for Golang
Go
13
star
59

pusher-channels-auth-example

A simple server exposing a pusher auth endpoint
JavaScript
13
star
60

pusher-platform-js

Pusher Platform client library for browsers and react native
TypeScript
13
star
61

stronghold

[DEPRECATED] A configuration service | owner: @willsewell
Haskell
12
star
62

pusher-twilio-example

CSS
12
star
63

prom-rule-reloader

Watches configmaps for prometheus rules and keeps prometheus in-sync
Go
12
star
64

sample-chatroom-ios-chatkit

How to make an iOS Chatroom app using Swift and Chatkit
PHP
11
star
65

electron-desktop-starter-template

JavaScript
11
star
66

chatkit-server-ruby

Ruby server SDK for Chatkit
Ruby
11
star
67

realtime-visitor-tracker

Realtime location aware visitor tracker for a web site or application
PHP
11
star
68

push-notifications-server-java

Pusher Beams Java Server SDK
Kotlin
10
star
69

android-slack-clone

Android chat application, built with Chatkit
Kotlin
10
star
70

filtrand

JavaScript
10
star
71

vault

Front-end pattern library
Ruby
9
star
72

push-notifications-go

Pusher Beams Go Server SDK
Go
9
star
73

pusher-platform-android

Pusher Platform SDK for Android
Kotlin
9
star
74

git-store

Go git abstraction for use in Kubernetes Controllers
Go
8
star
75

pusher-platform-swift

Swift SDK for Pusher platform products
Swift
8
star
76

realtime_survey_complete

JavaScript
8
star
77

docs

The all new Pusher docs, powered by @11ty and @vercel
CSS
8
star
78

push-notifications-server-swift

Pusher Beams Swift Server SDK
Swift
8
star
79

pusher-python-rest

Python client to interact with the Pusher REST API. DEPRECATED in favour of https://github.com/pusher/pusher-http-python
Python
8
star
80

real-time-progress-bar-tutorial

Used inthe realtime progress bar tutorial blog post - http://blog.pusher.com
JavaScript
7
star
81

pusher-channels-chunking-example

HTML
7
star
82

pusher-http-swift

Swift library for interacting with the Pusher Channels HTTP API
Swift
7
star
83

feeds-client-js

JS client for Pusher Feeds
JavaScript
6
star
84

pusher-test

Simple website which allows manual testing of pusher-js versions
JavaScript
6
star
85

java-websocket

A fork of https://github.com/TooTallNate/Java-WebSocket | owner=@zmarkan
HTML
6
star
86

bridge-troll

A Troll that ensures files don't change
Go
5
star
87

navarchos

Node replacing controller
Go
5
star
88

realtime-notifications-tutorial

Create realtime notifications in minutes, not days =)
4
star
89

pusher-socket-protocol

Protocol for pusher sockets
HTML
4
star
90

icanhazissues

Github issues kanban
JavaScript
4
star
91

textsync-server-node

[DEPRECATED] A node.js library to simplify token generation for TextSync authorization endpoints.
TypeScript
4
star
92

pusher_tutorial_realtimeresults

JavaScript
3
star
93

pusher-js-diagnostics

JavaScript
3
star
94

react-rest-api-tutorial

Accompanying tutorial for consuming RESTful APIs in React
CSS
3
star
95

testing

Configuration for Pusher's Open Source Prow instance
Go
3
star
96

feeds-server-node

The server Node SDK for Pusher Feeds
JavaScript
3
star
97

spacegame_example

Simple example of a space game using node.js and Pusher
JavaScript
3
star
98

chatkit-quickstart-swift

A project to get started with Chatkit.
Swift
2
star
99

pusher-whos-in

Ruby
2
star
100

chatkit-android-public-demo

This will hold the demo app for chatkit android. Owner: @daniellevass
Kotlin
2
star