Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 33 lines (26 sloc) 0.922 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
import json
from sockjs.tornado import SockJSConnection
from .models import Message


class ChatConnection(SockJSConnection):
    _connected = set()

    def on_open(self, request):
        #print "OPEN"
        #print request.get_cookie('name')
        self._connected.add(self)
        for each in Message.objects.all().order_by('date')[:10]:
            self.send(self._package_message(each))

    def on_message(self, data):
        data = json.loads(data)
        #print "DATA", repr(data)
        msg = Message.objects.create(
            name=data['name'],
            message=data['message']
        )
        self.broadcast(self._connected, self._package_message(msg))

    def on_close(self):
        #print "CLOSE"
        self._connected.remove(self)

    def _package_message(self, m):
        return {'date': m.date.strftime('%H:%M:%S'),
                'message': m.message,
                'name': m.name}
Something went wrong with that request. Please try again.