django push notification example using socket full exmaple with html template 2023 using channels
Here is an example of how to implement push notifications using Django Channels with a HTML template:
-
Install required packages:
- Django Channels:
pip install channels - Redis:
pip install channels_redis
- Django Channels:
-
Create a new Django project and app:
$ django-admin startproject myproject $ cd myproject $ python manage.py startapp myapp -
Configure Django Channels in
settings.py:INSTALLED_APPS = [ ... 'channels', 'myapp', ] CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('localhost', 6379)], }, }, } -
Create a new file
routing.pyin the project directory:from django.urls import path from myapp.consumers import NotificationConsumer websocket_urlpatterns = [ path('ws/notifications/', NotificationConsumer.as_asgi()), ] -
Update
asgi.pyto include the routing configuration:import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from myproject import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter(routing.websocket_urlpatterns), }) -
Create a new file
consumers.pyin themyappdirectory:from channels.generic.websocket import AsyncWebsocketConsumer import json class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send notification to all connected clients await self.channel_layer.group_send( 'notifications', { 'type': 'notification', 'message': message } ) async def notification(self, event): message = event['message'] # Send notification to current client await self.send(text_data=json.dumps({ 'message': message })) -
Update the
urls.pyfile in the project directory:from django.urls import path from myapp.views import HomeView urlpatterns = [ path('', HomeView.as_view(), name='home'), ] -
Create a new file
views.pyin themyappdirectory:from django.views.generic import TemplateView class HomeView(TemplateView): template_name = 'home.html' -
Create a new file
home.htmlin thetemplatesdirectory:<!DOCTYPE html> <html> <head> <title>Push Notifications Example</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var ws_path = ws_scheme + '://' + window.location.host + '/ws/notifications/'; var socket = new WebSocket(ws_path); socket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data.message; // Display the received notification $('#notification').text(message); }; </script> </head> <body> <h1>Push Notifications Example</h1> <div id="notification"></div> </body> </html> -
Start the development server:
$ python manage.py runserver
Now, when you open the homepage (http://localhost:8000/), it will connect to the WebSocket and display any received notifications in the <div id="notification"> element. You can send notifications by using JavaScript to send a message to the WebSocket endpoint (/ws/notifications/). For example:
socket.send(JSON.stringify({
'message': 'New notification!'
}));
Note: Make sure Redis is running on localhost:6379 as configured in settings.py
原文地址: https://www.cveoy.top/t/topic/hJ3C 著作权归作者所有。请勿转载和采集!