← Back to Journal

Websocket with Flask and Gevent

Posted on 28 October 2012

Ubik, package manager for Unix

If you follow me on Github you have maybe already seen that I currently develop a package manager for Unix, Ubik.

In order to test my API, I create a WebUI for Ubik and the websockets comes to me. My two prefered web framework are Django and Flask, but I need a lightweight web app, so welcome to Flask.

Node.js, blah, blah

Ok, I have many many times hear good things about Node.js and Socket.io, no doubt. But my focus is to do a lightweight and full Python implemented application.

So, tools are:

By the way, gevent-socketio seems to be a solid socket.io Python implementation.

App presentation

This is my Flask app structure:

requirements.txt

__init__.py

This is the app core, create your app, import every shared object you want to use into your app, like databases, etc.

And don’t forget to import views at the end to avoid circular imports.

websocket.py

All your websocket stuff could be here, this is the websocket handler. Messages from browser arrived here, and you can easily send message throught websocket with send method from ws object.

Use json, please.

views.py

Simple flask view to index.html template.

runserver.py

Run your app with this script. It import your app and feed WSGIServer with it.

index.html

And a quick Javascript websocket example.

All can find all this stuff in this repository. Thanks to tzangms.

What now?

Play websockets with Flask and Python is fun !

I will continue to improve Ubik webui with websocket and you have to take a look at the 0.2 branch. Bunch of new features is coming !