Web-socket connection. User online.

Simple consumer online/online_consumer.py

Add the consumer in the app.

Create a login function.

Create a new model with socket connections online/models.py.

And define a method to create a record unique by socket id.

Make and apply migrations.

from channels.generic.websocket import WebsocketConsumer
import json

class OnlineConsumer(WebsocketConsumer):

    def connect(self):
        print('Connnect!!!')
        self.accept()
        self.send(text_data=json.dumps({ \
            'type': 'online:ping', \
            'payload': 'ping from server' \
            } \
        ))

    def disconnect(self, close_code):
        # Channel.objects.filter(name=self.channel_name).delete()
        print('DISCONNECT!!! ONLINE')

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        print(text_data_json)
from channels.routing import ProtocolTypeRouter, URLRouter
from online.online_consumer import OnlineConsumer
from django.urls import re_path
from channels.auth import AuthMiddlewareStack


websocket_urlpatterns = [
    re_path(r'online/$', OnlineConsumer),
]

application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter(
            websocket_urlpatterns
        )
    ), 
})
admin
Потратить 2 кредита и начать обучение!
Задать вопрос, прокомментировать.