django push notification example using socket full exmaple with html template 2023
Here is an example of how you can implement push notifications using Django and Socket.IO with an HTML template.
- Install the required packages:
pip install django django-socketio
- Create a new Django project and app:
django-admin startproject push_notifications
cd push_notifications
python manage.py startapp notifications
- Update the project settings:
# settings.py
INSTALLED_APPS = [
...
'notifications',
'django_socketio',
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
SOCKETIO_HOST = 'localhost'
SOCKETIO_PORT = 8000
- Create a new HTML template:
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Push Notifications</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.js"></script>
</head>
<body>
<h1>Push Notifications</h1>
<div id="notification-container"></div>
<script>
var socket = io.connect('http://localhost:8000');
socket.on('notification', function(data) {
var notificationContainer = document.getElementById('notification-container');
var notification = document.createElement('div');
notification.innerHTML = data.message;
notificationContainer.appendChild(notification);
});
</script>
</body>
</html>
- Create a new Django view for the index page:
# views.py
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
- Create a new Django URL pattern for the index page:
# urls.py
from django.urls import path
from notifications import views
urlpatterns = [
path('', views.index, name='index'),
]
- Create a new Django Socket.IO event handler for push notifications:
# socketio_views.py
from django_socketio import events
@events.on_message(channel='^notification')
def push_notification(request, socket, context, message):
socket.send({'message': message})
- Update the project URL patterns to include the Socket.IO event handler:
# urls.py
from django.urls import path
from notifications import views
from django_socketio import events
urlpatterns = [
path('', views.index, name='index'),
]
socketio_events = [
events.on_message(channel='^notification')(views.push_notification),
]
- Start the development server:
python manage.py runserver
Now, when you visit http://localhost:8000/, you should see the index page with a notification container. To send a push notification, you can use the following code in another Django view or anywhere in your codebase:
# views.py or any other module
from django_socketio import broadcast
def send_notification(request):
message = 'New notification'
broadcast(message, channel='notification')
This will send a push notification to all connected clients, and the notification will be displayed in the container on the index page
原文地址: https://www.cveoy.top/t/topic/hJ3k 著作权归作者所有。请勿转载和采集!