Combining websockets and WSGI in a python app

Here is an example that does what you want:

  • https://github.com/tavendo/AutobahnPython/tree/master/examples/twisted/websocket/echo_wsgi

It runs a WSGI web app (Flask-based in this case, but can be anything WSGI conforming) plus a WebSocket server under 1 server and 1 port.

You can send WS messages from within Web handlers. Autobahn also provides PubSub on top of WebSocket, which greatly simplifies the sending of notifications (via WampServerProtocol.dispatch) like in your case.

  • http://autobahn.ws/python

Disclosure: I am author of Autobahn and work for Tavendo.


but I'm not sure about the architecture for mixing WSGI and websockets

I made it

use WSocket

Simple WSGI HTTP + Websocket Server, Framework, Middleware And App.

Includes

  • Server(WSGI) included - works with any WSGI framework
  • Middleware - adds Websocket support for any WSGI framework
  • Framework - simple Websocket WSGI web application framework
  • App - Event based app for Websocket communication When external server used, some clients like Firefox requires http 1.1 Server. for Middleware, Framework, App
  • Handler - adds Websocket support to wsgiref(python builtin WSGI server)
  • Client -Coming soon...

Common Features

  • only single file less than 1000 lines
  • websocket sub protocol supported
  • websocket message compression supported (works if client asks)
  • receive and send pong and ping messages(with automatic pong sender)
  • receive and send binary or text messages
  • works for messages with or without mask
  • closing messages supported
  • auto and manual close

example using bottle web framework and WSocket middleware

from bottle import request, Bottle
from wsocket import WSocketApp, WebSocketError, logger, run
from time import sleep

logger.setLevel(10)  # for debugging

bottle = Bottle()
app = WSocketApp(bottle)
# app = WSocketApp(bottle, "WAMP")

@bottle.route("/")
def handle_websocket():
    wsock = request.environ.get("wsgi.websocket")
    if not wsock:
        return "Hello World!"

    while True:
        try:
            message = wsock.receive()
            if message != None:
                print("participator : " + message)
                
            wsock.send("you : "+message)
            sleep(2)
            wsock.send("you : "+message)
            
        except WebSocketError:
            break
            
run(app)