Skip to main content

Flask-Threaded-Sockets

Barebones WebSockets for your low-traffic Flask apps.

Simple usage of route decorator:

from flask import Flask
from flask_threaded_sockets import Sockets, ThreadedWebsocketServer


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__":
    srv = ThreadedWebsocketServer("0.0.0.0", 5000, app)
    srv.serve_forever()

Usage of Flask blueprints:

from flask import Flask, Blueprint
from flask_threaded_sockets import Sockets, ThreadedWebsocketServer


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__":
    srv = ThreadedWebsocketServer("0.0.0.0", 5000, app)
    srv.serve_forever()

Serving WebSockets in Python was really easy, if you used Gevent, AsyncIO, etc. Now it's easy if you just want to use a threaded development server.

Why would you ever want this?

This should not be used in deployed web apps with lots of requests expected! We developed this library for use in low-traffic IoT devices that benefit from using native Python threads

Almost every Python websocket tutorial out there will tell you to use an async library like AsyncIO, Gevent, Tornado etc. For virtually all applications, this is absolutely true. These async libraries allow you to handle a huge number of concurrent requests, even long-running connections like websockets, with minimal overhead.

In these cases, native threading is heavily discouraged. Most threaded production servers will use a small pool of threads to handle concurrency, and websockets will quickly saturate this pool. Async concurrency libraries get around this by allowing a virtually unlimited number of concurrent requests to be processed.

One way to use native threads without risking pool saturation would be to spawn a thread per client, however it's obvious to see why this would be problematic for large public web apps: One thread per client will quickly lead to an infeasible number of native threads, introducing a huge context-switching overhead.

However, for small services, such as local WoT devices, this is absolutely fine. If you only expect a small (<50) number of simultaneous connections, native threads are perfectly viable as a concurrency provider. Moreover, unlike most async libraries, you're able to easily integrate existing code without having to add async/await keywords, or monkey-patch libraries. For instrument control, this is ideal. We get the full capabilities of Python threading, and it's synchronisation primitives, unmodified use of existing device control code, and no need for monkey-patching.

Installation

To install Flask-Sockets, simply:

pip install flask-threaded-sockets

WebSocket interface

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

Metadata

Release files for flask-threaded-sockets 0.3.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flask-threaded-sockets 0.3.2
File Size Uploaded Provenance Actions
flask_threaded_sockets-0.3.2.tar.gz 29.1 kB Without provenance Details for flask_threaded_sockets-0.3.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for flask-threaded-sockets 0.3.2
File Interpreter ABI Platform Actions
flask_threaded_sockets-0.3.2-py3-none-any.whl Python 3 none any Details for flask_threaded_sockets-0.3.2-py3-none-any.whl

Total release size: 59.0 kB

Release files / flask_threaded_sockets-0.3.2.tar.gz

Download URL flask_threaded_sockets-0.3.2.tar.gz
Size 29.1 kB
Tags Source
SHA-256 checksum
How to use checksums
56517d33d1e8d34573a33abd728ec2cfbbf7e78a339f1bd30b31e8045bd68ad4
BLAKE2b-256 checksum
How to use checksums
3ce8f771f107c6d201b60f668f426901e71c82901bbfeb4f1056b4ed5a5705c8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.0.9 CPython/3.8.5 Windows/10

Release files / flask_threaded_sockets-0.3.2-py3-none-any.whl

Download URL flask_threaded_sockets-0.3.2-py3-none-any.whl
Size 29.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2c4af113f806b2338a1d572d8713b5c7f5f32e0c1763e426a3982d3c0c5f3d08
BLAKE2b-256 checksum
How to use checksums
a30c7bf9fc5f9fe133a7375f28e4a6df13074cb46fb07d9d408ba1dc5207bb03
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.0.9 CPython/3.8.5 Windows/10

Security for flask-threaded-sockets 0.3.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page