django push notification example using socket full exmaple using html template using channels without redis
To implement push notifications using Django channels without Redis, you can use the ASGI server provided by Django channels, which is based on Daphne. Here's an example of how you can set it up:
-
Install Django channels and its dependencies:
pip install channels -
Create a new Django project:
django-admin startproject push_notifications cd push_notifications -
Create a new Django app:
python manage.py startapp notifications -
Update the project's
settings.pyfile:INSTALLED_APPS = [ # ... 'channels', 'notifications', ] CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } ASGI_APPLICATION = 'push_notifications.routing.application' -
Create a new file
routing.pyin the project's root directory:from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from notifications.consumers import NotificationConsumer application = ProtocolTypeRouter({ 'websocket': URLRouter([ path('ws/notifications/', NotificationConsumer.as_asgi()), ]), }) -
Create a new file
consumers.pyinside thenotificationsapp directory:import json from channels.generic.websocket import AsyncWebsocketConsumer class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'notifications' await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): data = json.loads(text_data) message = data.get('message') await self.channel_layer.group_send( self.room_group_name, { 'type': 'notify', 'message': message } ) async def notify(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) -
Update the
urls.pyfile of the project:from django.urls import path from notifications import views urlpatterns = [ # ... path('notifications/', views.notifications, name='notifications'), ] -
Create a new file
views.pyinside thenotificationsapp directory:from django.shortcuts import render def notifications(request): return render(request, 'notifications.html') -
Create a new HTML template file
notifications.htmlinside thetemplatesdirectory of thenotificationsapp:<!DOCTYPE html> <html> <head> <title>Push Notifications</title> </head> <body> <h1>Push Notifications</h1> <input type="text" id="messageInput" placeholder="Enter a message"> <button id="sendButton">Send</button> <script> var socket = new WebSocket('ws://' + window.location.host + '/ws/notifications/'); socket.onmessage = function(e) { var data = JSON.parse(e.data); showMessage(data.message); }; document.getElementById('sendButton').addEventListener('click', function() { var message = document.getElementById('messageInput').value; socket.send(JSON.stringify({ 'message': message })); }); function showMessage(message) { var div = document.createElement('div'); div.innerHTML = message; document.body.appendChild(div); } </script> </body> </html> -
Run the development server:
python manage.py runserver
Now, you can access the push notifications page at http://localhost:8000/notifications/. Enter a message in the input field and click the "Send" button. The message will be sent to all connected clients and will be displayed on the page in real-time
原文地址: https://www.cveoy.top/t/topic/hJ4S 著作权归作者所有。请勿转载和采集!