A lot of websites display notifications in one form or another these days. Facebook shows the new message notification, Gmail have the new mail notifications (with the support of browser notifications).
I was asked today how hard it would be to implement a real-time notification system. The answer, as it turns out, is: not very hard at all.
Setup
This could easily be implemented in an existing application but since I'm doing this from scratch I'll go through the steps of setting everything up.
First step is to install SwampDragon.
pip install swampdragon
Models
We store the notification as a model. This way we can load existing notification when the user loads the page the first time.
from django.db import models
from swampdragon.models import SelfPublishModel
from .serializers import NotificationSerializer
class Notification(SelfPublishModel, models.Model):
serializer_class = NotificationSerializer
message = models.TextField()
Javascript
The last piece of the puzzle is the JavaScript.
var dragon = new VanillaDragon({onopen: onOpen, onchannelmessage: onChannelMessage});
// ... logic implementation ...
To test this out, open a web browser to http://localhost:8000. Open a second terminal and run python server.py to start the SwampDragon backend.