How to use the channels.generic.websocket.AsyncWebsocketConsumer function in channels

To help you get started, we’ve selected a few channels examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github VirtualJudge / VirtualJudge / ws / consumers.py View on Github external
import json

from channels.generic.websocket import AsyncWebsocketConsumer


class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.chat_type = self.scope['url_route']['kwargs']['chat_type']
        self.room_group_name = 'chat_%s' % self.chat_type

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
github ModelChimp / modelchimp / modelchimp / views / consumers / tracker.py View on Github external
from settings import settings
from datetime import datetime

from django.utils import timezone
from django.contrib.auth.models import AnonymousUser

from channels.db import database_sync_to_async
from channels.auth import login
from channels.generic.websocket import AsyncWebsocketConsumer

from modelchimp.models.membership import Membership
from modelchimp.models.experiment import Experiment
from modelchimp.enum import ClientEvent, ExperimentStatus


class TrackerConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        #self.experiment_id = self.scope['url_route']['kwargs']['experiment_id']
        self.project = ''

        await self.accept()
        await self.send(text_data=json.dumps({
            'type': 'ACCEPTED',
            'message': 'Accepted'
        }))

    async def disconnect(self, close_code):
        pass

    # Receive message from WebSocket
    async def receive(self, text_data):
        data_json = json.loads(text_data)
github czue / celery-progress / celery_progress / websockets / consumers.py View on Github external
from channels.generic.websocket import AsyncWebsocketConsumer
import json

from celery_progress.backend import Progress


class ProgressConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.task_id = self.scope['url_route']['kwargs']['task_id']

        await self.channel_layer.group_add(
            self.task_id,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(
            self.task_id,
            self.channel_name
        )
github overshard / timestrap / sockets / consumers.py View on Github external
import json

from channels.generic.websocket import AsyncWebsocketConsumer


class UpdateConsumer(AsyncWebsocketConsumer):
    """
    Goes with our core signal that, on model update, sends a message to all
    channels in the group to sync the UI.
    """

    async def connect(self):
        await self.accept()
        await self.channel_layer.group_add("sync_clients", self.channel_name)

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard("sync_clients", self.channel_name)

    async def sync_clients_save(self, event):
        await self.send(json.dumps({"model": event["model"]}))

    async def sync_clients_delete(self, event):
github cloudera / hue / desktop / libs / notebook / src / notebook / consumer.py View on Github external
import json
import logging

from desktop.conf import has_channels


LOG = logging.getLogger(__name__)


if has_channels():
  from asgiref.sync import async_to_sync
  from channels.generic.websocket import AsyncWebsocketConsumer
  from channels.layers import get_channel_layer


  class EditorConsumer(AsyncWebsocketConsumer):

    async def connect(self):
      await self.accept()

      LOG.info('User %(user)s connected to WS Editor.' % self.scope)

      await self.send(
        text_data=json.dumps({
          'type': 'channel_name',
          'data': self.channel_name,
          'accept': True
        })
      )


    async def task_progress(self, event):
github Novacer / alpharithmic-trading / backend / backend / consumers.py View on Github external
from channels.generic.websocket import AsyncWebsocketConsumer
import json


class LogsConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
github django / channels / channels / security / websocket.py View on Github external
else:
            return None


def AllowedHostsOriginValidator(application):
    """
    Factory function which returns an OriginValidator configured to use
    settings.ALLOWED_HOSTS.
    """
    allowed_hosts = settings.ALLOWED_HOSTS
    if settings.DEBUG and not allowed_hosts:
        allowed_hosts = ["localhost", "127.0.0.1", "[::1]"]
    return OriginValidator(application, allowed_hosts)


class WebsocketDenier(AsyncWebsocketConsumer):
    """
    Simple application which denies all requests to it.
    """

    async def connect(self):
        await self.close()
github django / channels / channels / generic / websocket.py View on Github external
await self.channel_layer.group_discard(group, self.channel_name)
        except AttributeError:
            raise InvalidChannelLayerError(
                "BACKEND is unconfigured or doesn't support groups"
            )
        await self.disconnect(message["code"])
        raise StopConsumer()

    async def disconnect(self, code):
        """
        Called when a WebSocket connection is closed.
        """
        pass


class AsyncJsonWebsocketConsumer(AsyncWebsocketConsumer):
    """
    Variant of AsyncWebsocketConsumer that automatically JSON-encodes and decodes
    messages as they come in and go out. Expects everything to be text; will
    error on binary data.
    """

    async def receive(self, text_data=None, bytes_data=None, **kwargs):
        if text_data:
            await self.receive_json(await self.decode_json(text_data), **kwargs)
        else:
            raise ValueError("No text section for incoming WebSocket frame!")

    async def receive_json(self, content, **kwargs):
        """
        Called with decoded JSON content.
        """
github MAKENTNU / web / make_queue / views / stream / stream.py View on Github external
import json

from channels.generic.websocket import AsyncWebsocketConsumer
from django.conf import settings


class StreamConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['stream_name']
        self.room_group_name = 'stream_%s' % self.room_name

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,