Django + Tornado = Chat

Just finished up a quick one day project…  Was curious about Torando and since I’ve been playing with Django wondered about mixing the two…   Of course at one level there isn’t much reason to put django and tornado together since django has a “fine” webserver built in and Torando is all about async.

Thus you need to invent an app that requires async, traditional http chat with long polling is the trick.  So, pulling a demo from the NodeJS land and building a bunch of glue work I ended up with a working Django+Torando = Chat application.  Sorry there is no demo, since it looks and works pretty much like the NodeJS chat application (borrowed their UI and JS).

However if you want to check out the code take a look at this:

http://github.com/koblas/django-on-tornado

The key part that’s interesting is this ability to add asyn requests to a django handler:

from django_tornado.decorator import asynchronous

@asynchronous
def recv(request, handler) :
    response = {}

    if 'since' not in request.GET :
        return ChatResponseError('Must supply since parameter')
    if 'id' not in request.GET :
        return ChatResponseError('Must supply id parameter')

    id = request.GET['id']
    session = Session.get(id)
    if session :
        session.poke()

    since = int(request.GET['since'])

    def on_new_messages(messages) :
        if handler.request.connection.stream.closed():
            return
        handler.finish({ 'messages': messages, 'rss' : channel.size() })

    channel.query(handler.async_callback(on_new_messages), since)

Also read...

  • Ashley Russell

    thankyou, you code was AMAZINGLY helpful, much love!

  • Yifu Diao

    Very helpful code. One problem, when I try to port this to my project, I found that in DjangoHandler class, post() just calls get(), and this is probably the reason my log in form(which uses post) not working. Can you point to me how to implement the post method? Where to look at in Django source code?

    Another question is, will this handle traffic in production?

    Thanks and waiting for your response!

  • Pingback: Django | Pearltrees

  • Pingback: Homepage