Websocket support for django!

You know what WebSockets are? It's a new web protocol for bidirectional connections between the browser and your application server. This is a huge win over AJAX and plain HTTP since you don't need to establish a new connection for every tiny message.

Like TCP socket but for the web.

It's an exciting new technology - so I started experimenting with WebSockets and with my favourite webframework Django. Here is what I came up with, bundled into a reusable app called django-websocket.

What can I do with it?

You usually want to use WebSockets for single URLs - so the common design for making single views more powerful is by wrapping them with a decorator. Thats exactly how django-websocket will upgrade your views to accept websocket connections.

from django_websocket import require_websocket

# the decorator rejects all requests that aren't websockets
@require_websocket
def echo(request):
    while True:
        # wait() will return new messages as they arrive
        message = request.websocket.wait()
        # wait() returns None if the connection was closed by the client
        if message is None:
            return
        # simple method for sending messages
        request.websocket.send(message)

Above is a very basic example of an echo server that sends every message it receives back to the client.

You see its very easy to make websockets available. The decorator will attach a simple websocket-API-object to the request object. It has some primitive methods you can easily work with. Two of them are already used in the example above.

Another is for example request.websocket.read(). Unlike wait(), read() will not block your code if no messages are ready to be processed. It just returns None if new messages are received from the client.

Have a look into the documention to get an idea of the other methods that are available or to see more examples.

Explore

The project is still very experimental and has not been proved to be production ready. But its a lot of fun to work with. Dive into it and get creative!

I would really appreciate any feedback you can give. Flame, rant or make suggestions for improvements.

I'm especially interested in when you try to build something serious with django-websocket. Let me know about your awesome ideas and how it will make the django ecosystem even more colorful.


This is Websocket support for django! by Gregor Muellegger and was published on 20th July 2010.

Short url: http://gremu.net/BU

Tags: django, reusable-app, websocket

Back to the list page »


Flattr this blog if you like my work.

Know me …

Browse