,

Python – Simple Websockets Example using Flask and gevent

Below is a simple Websockets Echo Server using Flask and gevent 🙂

Installation

requirements.txt – easily build all depencies

cat > requirements.txt <<"_EOF_"
flask
greenlet
gevent
gevent-websocket
_EOF_

sudo pip install -U -r requirements.txt

websocket_echo_test.py - main server file

cat > websocket_echo_test.py <<"_EOF_"
# coding: utf-8
import os
import json
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
import flask
app = flask.Flask(__name__, template_folder='./')
app.secret_key = os.urandom(24)
app.debug = True
host,port='localhost',8000

@app.route('/')
def index():
    return flask.render_template('index.html', port=port)
def wsgi_app(environ, start_response):
    path = environ["PATH_INFO"]
    if path == "/":
        return app(environ, start_response)
    elif path == "/websocket":
        handle_websocket(environ["wsgi.websocket"])
    else:
        return app(environ, start_response)
def handle_websocket(ws):
    while True:
        message = ws.receive()
        if message is None:
            break
        message = json.loads(message)
        ws.send(json.dumps({'output': message['output']}))
if __name__ == '__main__':
    http_server = WSGIServer((host,port), wsgi_app, handler_class=WebSocketHandler)
    print('Server started at %s:%s'%(host,port))
    http_server.serve_forever()

_EOF_

index.html - HTML template

cat > index.html <<"_EOF_"










    
    

--
Websockets Echo Server using Gevent-websocket & Flask

_EOF_

Start Server

python websocket_echo_test.py

Browser URL


http://localhost:8000

References

1. Flask
2. Gevent
3. Websockets