Will & Skill Developers

Will & Skill Developers


Thoughts, snippets and ideas from the team at Will & Skill AB, Stockholm.

Hassan Mian
Author

Don't let someone else's opinion of you become your reality. - Les Brown

Share


Tags


avrt

Real Time Notifications with Firebase, Django and Backbone - Part 3

Before getting into part 3, lets have a quick recap: We've created a model We trigger a signal (event) everytime this model is saved We handle the signal and re…

Hassan MianHassan Mian

Before getting into part 3, lets have a quick recap:

  • We've created a model
  • We trigger a signal (event) everytime this model is saved
  • We handle the signal and render a notification to be sent to all of our subscribers.

In this part we will cover the following:

  • Sending our notification to Firebase

Sounds simple right? Well, it is!

Make sure you install firebase in your environment

pip install python-firebase

In part 2 we imported a function called send_notifications. We will start off this chapter by creating the file (notifications.py) containing that function. As you probably remember the file should be created under core/tasks

# notifications.py

from django.conf import settings
from firebase import firebase

FIREBASE_URL = settings.FIREBASE_URL

def send_notifications(subscribers, notification_markup):
	context = {'markup': notification_markup}
    fb = firebase.FirebaseApplication(FIREBASE_URL, None)
    
    for user in subscribers: 
	    url = '/users/%s/notification' % user.pk

	    try:
        	result = fb.post(url, context)
        
        except Exception as e:
	        print e
    	    print 'Firebase Notification not sent'

Pretty straight forward?

  • Import django settings
  • Import firebase
  • Get FIREBASE_URL from settings (we will specify this later on)
  • Wrap the markup in a dictionairy object (thats the way Firebase works)
  • Connect to firebase
  • For each subscriber, push a specific markup to their notifications endpoint.
  • Wrap everything up in a simple try/except.

For this to work, you need to add your firebase url to your django projects settings.py. We usually do something like this when developing:

SITE_URLS = {
	'DEV': 'http://my-cool-project-dev.willandskill.se',
	'LIVE': 'http://my-cool-project-live.willandskill.se'
}

FIREBASE_URLS = {
	'DEV': 'https://my-cool-project-dev.firebaseio.com',
	'LIVE': 'https://my-cool-project-live.firebaseio.com'
}

SITE_URL = SITE_URLS['DEV']
FIREBASE_URL = FIREBASE_URLS['DEV']

I specified a SITE_URL aswell because we refered to it in Part 2.

So now you should have a connection to firebase and will be pushing notification to firebase everytime you create a blog post.

In part 4 I'll walk you through how you can render these notification in your Backbone project.

Hassan Mian
Author

Hassan Mian

Don't let someone else's opinion of you become your reality. - Les Brown

View Comments