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
Python Socket.IO server and client

python-socketio Python implementation of the Socket.IO realtime client and server. Version compatibility The Socket.IO protocol has been through a num

Miguel Grinberg 3.2k Dec 31, 2022
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
An IPC based on Websockets, fast, stable, and reliable

winerp An IPC based on Websockets. Fast, Stable, and easy-to-use, for inter-communication between your processes or discord.py bots. Key Features Fast

Black Thunder 5 Aug 09, 2022
Library for building WebSocket servers and clients in Python

What is websockets? websockets is a library for building WebSocket servers and clients in Python with a focus on correctness and simplicity. Built on

Aymeric Augustin 4.3k Jan 04, 2023
This websocket program is for data transmission between server and client. Data transmission is for Federated Learning in Edge computing environment.

websocket-for-data-transmission This websocket program is for data transmission between server and client. Data transmission is for Federated Learning

9 Jul 19, 2022
一款为 go-cqhttp 的正向 WebSocket 设计的 Python SDK

Nakuru Project 一款为 go-cqhttp 的正向 WebSocket 设计的 Python SDK 在 kuriyama 的基础上改动 项目名来源于藍月なくる,图标由せら绘制 食用方法 将 nakuru 文件夹移至 Python 的 Lib/site-packages 目录下。

35 Dec 21, 2022
A Security Tool for Enumerating WebSockets

STEWS: Security Testing and Enumeration of WebSockets STEWS is a tool suite for security testing of WebSockets This research was first presented at OW

175 Jan 01, 2023
WebSocket emulation - Python server

SockJS-tornado server SockJS-tornado is a Python server side counterpart of SockJS-client browser library running on top of Tornado framework. Simplif

Serge S. Koval 854 Nov 19, 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
Discord.py Connect to Discord voice call with websocket

Discord.py Connect to Discord voice call with websocket

WoahThatsHot 3 Apr 22, 2022
Websockify is a WebSocket to TCP proxy/bridge. This allows a browser to connect to any application/server/service. Implementations in Python, C, Node.js and Ruby.

websockify: WebSockets support for any application/server websockify was formerly named wsproxy and was part of the noVNC project. At the most basic l

noVNC 3.3k Jan 03, 2023
Async (trio) KuCoin minimal REST API + Websocket

Minimal Async KuCoin REST API + WebSocket using trio Coded by π ([email protected] TG: @p

Pi 2 Oct 23, 2022
Burgeramt-appointments-websockets - Fetch Bürgeramt appointments and broadcast them via websockets

Bürgeramt appointment finder This server looks for Bürgeramt appointment every f

74 Dec 19, 2022
Terminals served by tornado websockets

This is a Tornado websocket backend for the Xterm.js Javascript terminal emulator library. It evolved out of pyxterm, which was part of GraphTerm (as

Project Jupyter 332 Dec 27, 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
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
Get realtime updates in your mobile/web app from frappe and erpnext

Fsocket Extend frappe's websocket server using socket.io and redis Installation Use frappe bench to add fsocket in your project $ bench get-app https:

21 Sep 25, 2022
A simple texts communication platform using pygame and sockets.

Python Tchat A simple texts communication platform using pygame and sockets. How to install ? You need a python 3.8.6 server with at least one opened

Yohann Boniface 7 Jan 23, 2022
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