Sunday, November 3, 2013

Real-time interaction using PubNub


Problem:

We have an app that needs real-time interaction with its data and users

For example:
  • chat feature
  • notification feature
  • real-time check for teacher attendance late submits

Answer:

PubNub makes this easy for you.


Sample App:

Here is a simple app that checks that a teacher has already submitted their attendance. Thus, removing his/her name from a list of late submitees.


Sample PubNub Settings:

 PUBNUB_PUBLISH_KEY = 'sample_publish_key'
 PUBNUB_SUBSCRIBE_KEY = 'sample_subscribe_key'
 PUBNUB_SECRET_KEY = 'sample_secret_key'
 PUBNUB_SSL_ON = False
Here we set our PubNub settings taken from the PubNub developer site


Sample Models:

 from django.contrib.auth.models import User
 from django.db import models 
   
 class TeacherAttendance(models.Model):  
   teacher = models.ForeignKey(User)
   date = models.DateField()
   
   def __unicode__(self):  
     return self.teacher.username  
Here we create models for our sample app

Sample Signals:


 from django.conf import settings
 from django.db.models.signals import post_save
 from foo.pubnub import PubNub

 from bar.models import TeacherAttendance
 

 p = Pubnub(
     settings.PUBNUB_PUBLISH_KEY,
     settings.PUBNUB_SUBSCRIBE_KEY,
     settings.PUBNUB_SECRET_KEY,
     settings.PUBNUB_SSL_ON
 )

 def publish_teacher_attendance(sender, instance, **kwargs):
     data = {
         'teacher_id': instance.teacher.pk,
         'date': instance.date.strftime("%m/%d/%Y"),
     }
    
     p.publish({
         'channel': 'teacher-attendance-channel',
         'message': data,
     })

 post_save.connect(publish_teacher_attendance, sender=TeacherAttendance)
Here we call a signal after saving a TeacherAttendance object. On this signal, we publish a channel, 'teacher-attendance-channel' with a message carrying details of the object on save which we will use on the frontend


Sample JS:

 <script src="{% static 'js/pubnub.min.js' %}"></script>
 <script>
     (function() {
         var pubnub = PUBNUB.init({ subscribe_key : '{{PUBNUB_SUBSCRIBE_KEY}}' });
         pubnub.subscribe({
             channel : "teacher-attendance-channel",
             message : function(data){
                 if(data.date != '{{date|date:"m/d/Y"}}')
                     return;
                        
                 var teacher_id = data.teacher_id;
                 $('.late-teacher-list').find('#teacher-'+teacher_id).remove();
             }
         });
     } (jQuery));
 </script>
Here pubnub checks the client for channels that has been updated on the server. We use the details passed via the message and check whether the teacher has already submitted his/her attendance. If a teacher did already do a submit, his/her name will be removed from the late list.


So that's it. Here we have a sample app that removes the name of a teacher on a late list after he/she already submits an attendance.

No comments:

Post a Comment