Listening to notifications with WebSockets

Instead of the usual chat example, let's look at an example better suited to a social network to illustrate Channels—a notification app. The app will detect whenever a certain type of model is saved and push a notification to all clients (that is, browsers of all the connected users) in real time.

Assuming that Channels is properly installed and configured, we need to define all the protocol type routes in the routing.py file, as follows:

from channels.routing import ProtocolTypeRouter, URLRouter 
from django.urls import path 
from notifier.consumers import NotificationConsumer 
 
 
application = ProtocolTypeRouter({ 
    "websocket": URLRouter([ 
        path("notifications/", NotificationConsumer), 
    ]), 
}) 

HTTP requests ...

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.