Flask extension for Pusher

Related tags

Flask Flask-Pusher
Overview

Flask-Pusher

Build Status Coverage Status

Flask extension for Pusher. It is a thin wrapper around the official client, binding Flask app to Pusher client.

Installation

Install Flask-Pusher module from PyPI.

pip install Flask-Pusher

Configuration

The basic configuration for Pusher is app_id, key and secret. These values are available in Pusher web interface.

PUSHER_APP_ID = 'your-pusher-app-id'
PUSHER_KEY = 'your-pusher-key'
PUSHER_SECRET = 'your-pusher-secret'

You can connect to a custom host/port, with these configurations:

PUSHER_HOST = 'api.pusherapp.com'
PUSHER_PORT = '80'

The extension auto configure the Pusher encoder to use the app.json_encoder.

Usage

This extension simplify Pusher configuration and bind the client to your app.

from flask import Flask
from flask_pusher import Pusher

app = Flask(__name__)
pusher = Pusher(app)
# Use pusher = Pusher(app, url_prefix="/yourpath") to mount the plugin in another path

The extension gives you two ways to access the pusher client:

# you can just get the client from current_app
client = current_app.extensions["pusher"]

# or you can get it from the extension
client = pusher.client

In both cases, it is a reference to the pusher client.

client.trigger('channel_name', 'event', {
    'message': msg,
})

Check the docs for the Pusher python client here: http://pusher.com/docs/server_api_guide#/lang=python

Pusher authentication

Pusher has authenticated private and presence channels. Flask-Pusher create the /pusher/auth route to handle it. To support these authenticated routes, just decorate a function with @pusher.auth.

This function must return True for authorized and False for unauthorized users. It happens in the request context, so you have all Flask features, including for example the Flask-Login current user.

Set the PUSHER_AUTH configuration to change the auth endpoint. The default value is /auth.

from flask_login import current_user

@pusher.auth
def pusher_auth(channel_name, socket_id):
    if 'foo' in channel_name:
        # refuse foo channels
        return False
    # authorize only authenticated users
    return current_user.is_authenticated()

It also transparently supports batch auth, based on pusher-js-auth: https://github.com/dirkbonhomme/pusher-js-auth`. The authentication function is called for each channel in the batch.

Read more about user authentication here: http://pusher.com/docs/authenticating_users

Pusher channel data

Presence channels require channel_data. Flask-Pusher send by default the user_id with the socket_id, because it is a required field.

The @pusher.channel_data gives you a way to set other values. If a user_id key is returned, it overrides the default user_id.

from flask_login import current_user

@pusher.channel_data
def pusher_channel_data(channel_name, socket_id):
    return {
        "name": current_user.name
    }

Pusher webhooks

Pusher has webhooks to send websocket events to your server.

Flask-Pusher create the routes to handle these webhooks and validate the headers X-Pusher-Key and X-Pusher-Signature.

from flask import request

@pusher.webhooks.channel_existence
def channel_existence_webhook():
    print request.json

@pusher.webhooks.presence
def presence_webhook():
    print request.json

@pusher.webhooks.client
def client_webhook():
    print request.json

The JSON request is documented in Pusher docs: http://pusher.com/docs/webhooks

These webhooks routes are mounted in /pusher/events/channel_existence, /pusher/events/presence and /pusher/events/client. Configure your Pusher app to send webhooks to these routes.

Disclaimer

This project is not affiliated with Pusher or Flask.

You might also like...
An extension to add support of Plugin in Flask.

An extension to add support of Plugin in Flask.

Flask-Rebar combines flask, marshmallow, and swagger for robust REST services.

Flask-Rebar Flask-Rebar combines flask, marshmallow, and swagger for robust REST services. Features Request and Response Validation - Flask-Rebar reli

Flask-Starter is a boilerplate starter template designed to help you quickstart your Flask web application development.
Flask-Starter is a boilerplate starter template designed to help you quickstart your Flask web application development.

Flask-Starter Flask-Starter is a boilerplate starter template designed to help you quickstart your Flask web application development. It has all the r

Brandnew-flask is a CLI tool used to generate a powerful and mordern flask-app that supports the production environment.

Brandnew-flask is still in the initial stage and needs to be updated and improved continuously. Everyone is welcome to maintain and improve this CLI.

Flask Project Template A full feature Flask project template.

Flask Project Template A full feature Flask project template. See also Python-Project-Template for a lean, low dependency Python app. HOW TO USE THIS

A Fast API style support for Flask. Gives you MyPy types with the flexibility of flask
A Fast API style support for Flask. Gives you MyPy types with the flexibility of flask

Flask-Fastx Flask-Fastx is a Fast API style support for Flask. It Gives you MyPy types with the flexibility of flask. Compatibility Flask-Fastx requir

Flask-app scaffold, generate flask restful backend

Flask-app scaffold, generate flask restful backend

Flask pre-setup architecture. This can be used in any flask project for a faster and better project code structure.

Flask pre-setup architecture. This can be used in any flask project for a faster and better project code structure. All the required libraries are already installed easily to use in any big project.

flask-reactize is a boostrap to serve any React JS application via a Python back-end, using Flask as web framework.

flask-reactize Purpose Developing a ReactJS application requires to use nodejs as back end server. What if you want to consume external APIs: how are

Comments
  • Update flask_pusher.py

    Update flask_pusher.py

    Only make endpoints if its the first time making them, ignore "AssertionError: View function mapping is overwriting an existing endpoint function: pusher.auth" error.

    Sorry about all the updates, these are changes I've made manually for some time now but can't deploy to production like that. If you could do another release <3

    opened by ScriptProdigy 3
  • Support auth endpoint

    Support auth endpoint

    Private and presence channels require authentication. This extension can easily handle this requirement.

    @pusher.auth
    def f(channel_name, socket_id):
        # here you have access to Flask request context
        # return True if the user has a access to the channel_name
        return True
    
    enhancement 
    opened by iurisilvio 1
  • DeprecationWarning: Request.is_xhr

    DeprecationWarning: Request.is_xhr

    /home/travis/build/iurisilvio/Flask-Pusher/.tox/py37-E/lib/python3.7/site-packages/werkzeug/local.py:347: DeprecationWarning: Request.is_xhr is deprecated. Given that the X-Requested-With header is not a part of any spec, it is not reliable
      return getattr(self._get_current_object(), name)
    
    opened by iurisilvio 0
  • DeprecationWarning: inspect.getargspec()

    DeprecationWarning: inspect.getargspec()

    DeprecationWarning: inspect.getargspec() is deprecated, use inspect.signature() or inspect.getfullargspec()
      argspec = inspect.getargspec(_pusher.Pusher.__init__)
    /home/travis/build/iurisilvio/Flask-Pusher/.tox/py37-D/lib/python3.7/site-packages/werkzeug/local.py:347: DeprecationWarning: Request.is_xhr is deprecated. Given that the X-Requested-With header is not a part of any spec, it is not reliable
      return getattr(self._get_current_object(), name)
    
    opened by iurisilvio 0
Releases(v0.2)
Owner
Iuri de Silvio
Iuri de Silvio
flask-apispec MIT flask-apispec (🥉24 · ⭐ 520) - Build and document REST APIs with Flask and apispec. MIT

flask-apispec flask-apispec is a lightweight tool for building REST APIs in Flask. flask-apispec uses webargs for request parsing, marshmallow for res

Joshua Carp 617 Dec 30, 2022
MongoEngine flask extension with WTF model forms support

Flask-MongoEngine Info: MongoEngine for Flask web applications. Repository: https://github.com/MongoEngine/flask-mongoengine About Flask-MongoEngine i

MongoEngine 815 Jan 3, 2023
A caching extension for Flask

Flask-Caching Adds easy cache support to Flask. This is a fork of the Flask-Cache extension. Flask-Caching also includes the cache module from werkzeu

Peter Justin 774 Jan 2, 2023
Rate Limiting extension for Flask

Flask-Limiter Flask-Limiter provides rate limiting features to flask routes. It has support for a configurable backend for storage with current implem

Ali-Akber Saifee 922 Jan 8, 2023
SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).

Flask-SeaSurf SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF). CSRF vulnerabilities have been found in large and popular

Max Countryman 183 Dec 28, 2022
A flask extension using pyexcel to read, manipulate and write data in different excel formats: csv, ods, xls, xlsx and xlsm.

Flask-Excel - Let you focus on data, instead of file formats Support the project If your company has embedded pyexcel and its components into a revenu

null 247 Dec 27, 2022
flask extension for integration with the awesome pydantic package

Flask-Pydantic Flask extension for integration of the awesome pydantic package with Flask. Installation python3 -m pip install Flask-Pydantic Basics v

null 249 Jan 6, 2023
A Flask extension that enables or disables features based on configuration.

Flask FeatureFlags This is a Flask extension that adds feature flagging to your applications. This lets you turn parts of your site on or off based on

Rachel Greenfield 131 Sep 26, 2022
A Flask extension that enables or disables features based on configuration.

Flask FeatureFlags This is a Flask extension that adds feature flagging to your applications. This lets you turn parts of your site on or off based on

Rachel Greenfield 124 Jan 22, 2021
A Flask extension that enables or disables features based on configuration.

Flask FeatureFlags This is a Flask extension that adds feature flagging to your applications. This lets you turn parts of your site on or off based on

Rachel Greenfield 131 Sep 26, 2022