Elegant WebSockets for your Flask apps.

Overview

Flask-Sockets

Elegant WebSockets for your Flask apps.

http://farm4.staticflickr.com/3689/9755961864_577e32a106_c.jpg

Simple usage of route decorator:

from flask import Flask
from flask_sockets import Sockets


app = Flask(__name__)
sockets = Sockets(app)


@sockets.route('/echo')
def echo_socket(ws):
    while not ws.closed:
        message = ws.receive()
        ws.send(message)


@app.route('/')
def hello():
    return 'Hello World!'


if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
    server.serve_forever()

Usage of Flask blueprints:

from flask import Flask, Blueprint
from flask_sockets import Sockets


html = Blueprint(r'html', __name__)
ws = Blueprint(r'ws', __name__)


@html.route('/')
def hello():
    return 'Hello World!'

@ws.route('/echo')
def echo_socket(socket):
    while not socket.closed:
        message = socket.receive()
        socket.send(message)


app = Flask(__name__)
sockets = Sockets(app)

app.register_blueprint(html, url_prefix=r'/')
sockets.register_blueprint(ws, url_prefix=r'/')


if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
    server.serve_forever()

Combining WebSockets with Ajax (XHR) endpoints also comes handy with the support of session handling built-in to sockets as well. As an example you could use an Ajax login call which would create a new session and accordingly set a secure HttpOnly cookie to the browser. After authorization, you can connect to the WebSocket endpoint and reuse the session handling from Flask there as well (as shown here: https://pythonhosted.org/Flask-Session/). Access to other custom cookies is also possible via Flasks request.cookies property.

Serving WebSockets in Python was really difficult. Now it's not.

Installation

To install Flask-Sockets, simply:

$ pip install Flask-Sockets

Deployment

A custom Gunicorn worker is included to make deployment as friendly as possible:

$ gunicorn -k flask_sockets.worker hello:app

Production services are provided by gevent and gevent-websocket.

The given example can run standalone as main.

Anything that inserts wsgi.websocket into the WSGI environ is supported, but gevent-websocket is recommended.

Development / Testing

Because the Werkzeug development server cannot provide the WSGI environ with a websocket interface, it is not possible to run a Flask app using the standard app.run().

If you try to, Flask will still try to serve on all the specified routes, and throw a KeyError whenever a client tries to connect to a websocket route.

Instead, just use the included gunicorn worker (explained above), or anything that can insert wsgi.websocket into the WSGI environ.

WebSocket Interface

The websocket interface that is passed into your routes is provided by gevent-websocket. The basic methods are fairly straightforward — send, receive, send_frame, and close.

Release History

v0.2.1

v0.2.0

  • Add request context into the socket handler.
  • Fallback to Flask logic if websocket environment is not available.
  • Use Flask routing to allow for variables in URL

v0.1.0

  • Initial release.
Owner
Heroku Python Team
Python projects owned by Heroku.
Heroku Python Team
Websocket RPC and Pub/Sub for Python applications and microservices

wampy [whomp-ee] For a background as to what WAMP is, please see here. This is a Python implementation of WAMP using Gevent, but you can also configur

simon 121 Nov 22, 2022
Minecraft WebSocket

Minecraft-WebSocket Pythonでマインクラフトと通信します。 紹介動画 推奨設定 Minecraft Windows Edition (Education Edition) 1.17 以上 Python 3系(3.8.2で動作確認済み) 必要なモジュール ・asyncio ・w

Roii.py 2 Jul 07, 2022
Chat app for Django, powered by Django Channels, Websockets & Asyncio

Django Private Chat2 New and improved https://github.com/Bearle/django-private-chat Chat app for Django, powered by Django Channels, Websockets & Asyn

Bearle 205 Dec 30, 2022
Websocket 'broadcast' demo using FastAPI/Starlette

fastapi-websocket-broadcast An example of the familiar 'chat' websocket demo app, implemented in FastAPI / Starlette. Run with uvicorn app:app And th

Kit Thwaite 109 Nov 30, 2022
AWS API Gateway Websocket Asynchronous Notifications Pusher

AWS API Gateway Websocket Asynchronous Pusher Fast AWS API Gateway websockets notifications' pusher using Python AsyncIO for managing asynchronous and

OBytes 5 May 15, 2022
WebSocket client for Python

websocket-client The websocket-client module is a WebSocket client for Python. It provides access to low level APIs for WebSockets. All APIs are for s

3.1k Jan 02, 2023
Whatsapp Clone using django, django-channels and websocket

whatsapp-clone Whatsapp Clone using django, django-channels and websocket Features : Signup/Login One on One personal chat with other user Some screen

Anshu Pal 14 Dec 25, 2022
JINS MEME(2021年モデル)のJINS MEME LoggerをPythonのWebSocketサーバーで受信するサンプル

JINS-MEME-Python-WebSocketServer-Sample JINS MEME(2021年モデル)のJINS MEME LoggerをPythonのWebSocketサーバーで受信するサンプルです。 Logging Data 以下のデータに対応しています。 各データの定義はJIN

KazuhitoTakahashi 19 Apr 29, 2022
Discord.py Connect to Discord voice call with websocket

Discord.py Connect to Discord voice call with websocket

WoahThatsHot 3 Apr 22, 2022
Django Channels HTTP/WebSocket server

daphne Daphne is a HTTP, HTTP2 and WebSocket protocol server for ASGI and ASGI-HTTP, developed to power Django Channels. It supports automatic negotia

Django 1.9k Dec 31, 2022
Connects microservices through a mesh of websockets

WebMesh WebMesh is a WebSocket based communication library for microservices. It uses a WebSocket server based on wsproto that distributes clients on

Charles Smith 9 Apr 29, 2022
tiny multi-threaded socks4 server implemented in python2

tiny, multi-threaded socks4a server implemented in python2.

4 Sep 21, 2022
alien.py - Python interface to websocket endpoint of ALICE Grid Services

alien.py - Python interface to websocket endpoint of ALICE Grid Services Quick containerized testing: singularity

Adrian Sevcenco 6 Dec 14, 2022
Developer-friendly asynchrony for Django

Django Channels Channels augments Django to bring WebSocket, long-poll HTTP, task offloading and other async support to your code, using familiar Djan

Django 5.5k Jan 03, 2023
WebSocket implementation in Python built on top of websockets python library. Similar to Node.js's ws.

ws WebSocket implementation in Python built on top of websockets python library. Similar to Node.js's ws. Basic usage. server.py import ws server = w

AceExpert 7 Jun 27, 2022
Using python-binance to provide websocket data to freqtrade

The goal of this project is to provide an alternative way to get realtime data from Binance and use it in freqtrade despite the exchange used. It also uses talipp for computing

58 Jan 01, 2023
WebSocket and WAMP in Python for Twisted and asyncio

Autobahn|Python WebSocket & WAMP for Python on Twisted and asyncio. Quick Links: Source Code - Documentation - WebSocket Examples - WAMP Examples Comm

Crossbar.io 2.4k Jan 04, 2023
SocketIO 转发台,保持 botoy 能力和插件功能的同时,透传其接口,以此使用更灵活、生态更好的技术进行开发

bot_sio_transfer SocketIO 转发台,保持 botoy 能力和插件功能的同时,透传其接口,以此使用更灵活、生态更好的技术进行开发 Usage 请参考 botoy 文档接入本插件 Example 考虑一种图文混排场景,如何从复杂结构内快速获取第一张图片的 url ? ( 假设图片

OPQ Open Source Community 3 Oct 18, 2021
wssh ("wish") is a command-line utility/shell for WebSocket inpsired by netcat.

wssh ("wish") is a command-line utility/shell for WebSocket inspired by netcat

Jeff Lindsay 256 Nov 16, 2022
A websocket client for Source Filmmaker intended to trasmit scene and frame data to other applications.

SFM SOCK A websocket client for Source Filmmaker intended to trasmit scene and frame data to other applications. This software can be used to transmit

KiwifruitDev 2 Jan 08, 2022