Source

django_tutorial / django_tutorial / realtime_server.py

Full commit
from realtimemagic import RealTimeMagic

from realtimemagic.monitors.psql import PsqlMonitor
from realtimemagic.auth.contrib import DjangoAuthenticator, AuthenticationError

from django.conf import settings

from django_tutorial.apps.polls.models import Poll


class MyAppAuthenticator(DjangoAuthenticator):
    def check(self, conn, channel):
        try:
            user = self.get_user(conn)

            obj = Poll.objects.get(id=channel)
            if not obj.user_can_access(user):
                raise AuthenticationError(self.error_message)
        except Poll.DoesNotExist:
            raise AuthenticationError(self.error_message)

DB = settings.DATABASES['default']

logs = PsqlMonitor(database=DB['NAME'],
        user=DB['USER'], password=DB['PASSWORD'],
        host=DB['HOST'], port=DB['PORT'])


# To-do: Listen to redis directly. This is too complicated.
@logs.monitor('logs')
def log_changes(notification, pubsub):
    print "notification"
    print notification
    channel, message = notification.payload.split('=>', 1)
    pubsub.publish(channel, {'message': message})

if __name__ == '__main__':
    rtm = RealTimeMagic(local=settings.DEBUG)
    rtm.monitors.append(log_changes)
    rtm.authenticators['logs'].append(DjangoAuthenticator())
    rtm.start()