Flask extension for Pusher

Related tags

FlaskFlask-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
É uma API feita em Python e Flask que pesquisa informações em uma tabela .xlsx e retorna o resultado.

API de rastreamento de pacotes É uma API feita em Python e Flask que pesquisa informações de rastreamento de pacotes em uma tabela .xlsx e retorna o r

Marcos Beraldo Barros 4 Jun 27, 2021
Track requests to your Flask website with Matomo

Flask-Matomo Flask-Matomo is a library which lets you track the requests of your Flask website using Matomo (Piwik). Installation pip install flask-ma

Lucas Hild 13 Jul 14, 2022
Flask extension that takes care of API representation and authentication.

Flask-API-Utils Flask-API-Utils helps you to create APIs. It makes responses in appropriate formats, for instance, JSON. All you need to do is to retu

Marsel Mavletkulov 55 Aug 28, 2022
Companion code to my O'Reilly book "Flask Web Development", second edition.

Flasky This repository contains the source code examples for the second edition of my O'Reilly book Flask Web Development. The commits and tags in thi

Miguel Grinberg 8k Dec 27, 2022
docker-compose uWSGI nginx flask

docker-compose uWSGI nginx flask Note that this was tested on CentOS 7 Usage sudo yum install docker

Abdolkarim Saeedi 3 Sep 11, 2022
Flask Boilerplate - Paper Kit Design | AppSeed

Flask Paper Kit Open-Source Web App coded in Flask Framework - Provided by AppSeed Web App Generator. App Features: SQLite database SQLAlchemy ORM Ses

App Generator 86 Nov 29, 2021
A basic JSON-RPC implementation for your Flask-powered sites

Flask JSON-RPC A basic JSON-RPC implementation for your Flask-powered sites. Some reasons you might want to use: Simple, powerful, flexible and python

Cenobit Technologies 272 Jan 04, 2023
Are-You-OK is a Flask-based, responsive Web App to monitor whether the Internet Service you care about is still working.

Are-You-OK Are-You-OK is a Flask-based, responsive Web App to monitor whether the Internet Service you care about is still working. Demo-Preview Get S

Tim Qiu 1 Oct 28, 2021
Implement Instagram with flask

Blue club The place where manly men live and breathe. Move to Notion Move to Fig

3 Apr 07, 2022
A simple way to demo Flask apps from your machine.

flask-ngrok A simple way to demo Flask apps from your machine. Makes your Flask apps running on localhost available over the internet via the excellen

117 Dec 27, 2022
A simple demo of using aiogram + async sqlalchemy 1.4+

aiogram-and-sqlalchemy-demo A simple demo of using aiogram + async sqlalchemy 1.4+ Used tech: aiogram SQLAlchemy 1.4+ PostgreSQL as database asyncpg a

Aleksandr 68 Dec 31, 2022
Forum written for learning purposes in flask and sqlalchemy

Flask-forum forum written for learning purposes using SQLalchemy and flask How to install install requirements pip install sqlalchemy flask clone repo

Kamil 0 May 23, 2022
Lightweight library for providing filtering mechanism for your APIs using SQLAlchemy

sqlalchemy-filters-plus is a light-weight extendable library for filtering queries with sqlalchemy. Install pip install sqlalchemy-fitlers-plus Usage

Karami El Mehdi 38 Oct 05, 2022
Set up a modern flask web server by running one command.

Build Flask App · Set up a modern flask web server by running one command. Installing / Getting started pip install build-flask-app Usage build-flask-

Kushagra Bainsla 5 Jul 16, 2022
A flask app that turn image into ASCII art

ASCII art A flask app that turn image into ASCII art. This app has been deployed to https://motmaytinh.herokuapp.com Getting Started These instruction

Trần Ngọc Quý 1 Jan 13, 2022
This is a Flask web app which predicts fare of Flight ticket

Flight Fare Prediction: Table of Content Demo Overview Motivation Installation Deployement on Heroku Directory Tree Bug / Feature Request Future scope

Ayshwarya 1 Jan 24, 2022
Template for a rest app with flask, flask-rest and more...

Flask REST Template About the project (some comments): The ideia behind the project is to create an useful and simple template for an rest app . Besid

107 Nov 16, 2022
A simple example using Flask inside a container

This is a simple example of how create a container for a Python Flask Web Application using Docker.

Fazt Web 8 Aug 30, 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 U

248 Dec 26, 2022
HTTP security headers for Flask

Talisman: HTTP security headers for Flask Talisman is a small Flask extension that handles setting HTTP headers that can help protect against a few co

Google Cloud Platform 853 Dec 19, 2022