Django Real-Time Push Notifications with WebSockets and Channels
Here's an example of using Django with Django Channels and Redis to implement real-time push notifications using WebSockets:
- Install required packages:
pip install django channels redis
- Configure Django Channels by adding the following to your project's
settings.pyfile:
INSTALLED_APPS = [
...
'channels',
]
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels.layers.InMemoryChannelLayer',
},
}
- Create a new Django app for the push notifications:
python manage.py startapp push_notifications
- Inside the
push_notificationsapp, create a new file calledconsumers.pywith the following content:
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class PushNotificationConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.group_name = 'push_notifications'
# Join the group
await self.channel_layer.group_add(
self.group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave the group
await self.channel_layer.group_discard(
self.group_name,
self.channel_name
)
async def receive(self, text_data):
# Send the received message to all connected clients
await self.channel_layer.group_send(
self.group_name,
{
'type': 'push_notification',
'message': text_data
}
)
async def push_notification(self, event):
# Send the received message to the WebSocket
await self.send(text_data=json.dumps(event['message']))
- Update your project's
routing.pyfile to include the routing configuration for the push notifications:
from django.urls import re_path
from push_notifications import consumers
websocket_urlpatterns = [
re_path(r'ws/push-notifications/$', consumers.PushNotificationConsumer.as_asgi()),
]
- In your main
urls.pyfile, include the routing configuration for the push notifications:
from django.urls import include, path
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
...
path('push-notifications/', include('push_notifications.urls')),
...
]
- Create a JavaScript file
push_notifications.jsin your static files directory with the following content:
const socket = new WebSocket('ws://localhost:8000/ws/push-notifications/');
socket.onmessage = function (e) {
const data = JSON.parse(e.data);
console.log('Received push notification:', data);
// Handle the received push notification
};
socket.onclose = function (e) {
console.error('Socket closed unexpectedly');
};
socket.onopen = function (e) {
console.log('Socket connected');
};
function sendPushNotification(message) {
socket.send(JSON.stringify(message));
}
- Include the JavaScript file in your HTML template:
<script src="{% static 'push_notifications.js' %}"></script>
- Finally, in your Django views or models, you can send push notifications by calling the
sendPushNotificationfunction:
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
def send_push_notification(message):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)('push_notifications', {
'type': 'push_notification',
'message': message
})
Now, whenever you call the send_push_notification function with a message, it will be sent to all connected WebSocket clients and can be handled on the client-side in the onmessage event handler.
Note: This example uses an in-memory channel layer for simplicity. In production, you should use a more scalable channel layer like Redis. You can find more information about that in the Django Channels documentation.
原文地址: http://www.cveoy.top/t/topic/ps8o 著作权归作者所有。请勿转载和采集!