How to use the channels.generic.websocket.WebsocketConsumer 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 tethysplatform / tethys / tests / apps / tethysapp-test_app / tethysapp / test_app / controllers.py View on Github external
def callback(attr: str, old: Any, new: Any) -> None:
        if new == 1:
            data['y'] = [0, 10, 20, 30, 40, 50]
        else:
            data['y'] = [i * new for i in [0, 10, 20, 30, 40, 50]]
        source.data = ColumnDataSource(data=data).data
        plot.y_range.end = max(data['y'])

    slider = Slider(start=1, end=5, value=1, step=1, title="Test App Bokeh + Channels Controller")
    slider.on_change("value", callback)

    doc.add_root(column(slider, plot))


class TestWS(WebsocketConsumer):
    def connect(self):
        self.accept()

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['client_message']

        self.send(text_data=json.dumps({
            'server_message': message
        }))

    def disconnect(self, close_code):
        pass
github django / channels / tests / test_testing.py View on Github external
self.accept()

    def receive(self, text_data=None, bytes_data=None):
        self.send(text_data=text_data, bytes_data=bytes_data)


class ErrorWebsocketApp(WebsocketConsumer):
    """
    Barebones WebSocket ASGI app for error testing.
    """

    def receive(self, text_data=None, bytes_data=None):
        pass


class KwargsWebSocketApp(WebsocketConsumer):
    """
    WebSocket ASGI app used for testing the kwargs arguments in the url_route.
    """

    def connect(self):
        self.accept()
        self.send(text_data=self.scope["url_route"]["kwargs"]["message"])


@pytest.mark.asyncio
async def test_websocket_communicator():
    """
    Tests that the WebSocket communicator class works at a basic level.
    """
    communicator = WebsocketCommunicator(SimpleWebsocketApp, "/testws/")
    # Test connection
github IMGIITRoorkee / omniport-backend / core / protocol_tests / consumers.py View on Github external
import json
from json import JSONDecodeError

from channels.generic.websocket import WebsocketConsumer


class PingPong(WebsocketConsumer):
    """
    Replies with a 'Pong' for every 'Ping' and a 'Ping' for every 'Pong'
    """

    def connect(self):
        """
        Process the connection request sent by a socket instance
        """

        self.accept()

    def disconnect(self, _):
        """
        Process the disconnection of a socket instance
        :param _: the code indicating the reason for disconnection
        """
github raveberry / raveberry / core / state_handler.py View on Github external
def state_dict(self):
        """Returns a dictionary containing all state of this class."""
        raise NotImplementedError()

    def get_state(self, _request):
        """Returns the state of this class as a json dictionary for clients to use."""
        state = self.state_dict()
        return JsonResponse(state)

    def update_state(self):
        """Sends an update event to all connected clients."""
        send_state_event(self.state_dict())


class StateConsumer(WebsocketConsumer):
    """Handles connections with websocket clients."""

    def connect(self):
        async_to_sync(self.channel_layer.group_add)("state", self.channel_name)
        self.accept()

    def disconnect(self, code):
        async_to_sync(self.channel_layer.group_discard)("state", self.channel_name)

    def receive(self, text_data=None, bytes_data=None):
        pass

    # Receive message from room group
    def state_update(self, event):
        """Receives a message from the room group and sends it back to the websocke."""
        # Send message to WebSocket
github rajasimon / beatserver / examples / examples / consumers.py View on Github external
import json

from asgiref.sync import async_to_sync
from channels.generic.websocket import SyncConsumer, WebsocketConsumer


class PrintConsumer(SyncConsumer):

    def test_print(self, message):
        async_to_sync(self.channel_layer.group_send)(
            "stream", {"type": "stream.message", 'message': message})


class StreamConsumer(WebsocketConsumer):
    def connect(self):
        self.room_group_name = 'stream'

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

        self.accept()


    def disconnect(self, close_code):
        pass

    def receive(self, text_data):
github richtier / alexa-browser-client / alexa_browser_client / consumers.py View on Github external
on_command_started=self.handle_command_started,
            on_command_finished=self.handle_command_finished,
        )

    def receive(self, text_data=None, bytes_data=None):
        super().receive(text_data=text_data, bytes_data=bytes_data)
        self.audio_lifecycle.extend_audio(bytes_data)

    def handle_command_started(self):
        self.send_status(constants.EXPECTING_COMMAND)

    def handle_command_finished(self):
        self.send_status(constants.EXPECTING_WAKEWORD)


class AlexaConsumer(LifecycleMixin, AlexaClientMixin, WebsocketConsumer):

    dialog_request_id = None

    def receive(self, text_data=None, bytes_data=None):
        if text_data == 'ExpectSpeech':
            self.audio_lifecycle.handle_command_started(None)
        else:
            super().receive(text_data=text_data, bytes_data=bytes_data)

    def send_status(self, message_id):
        self.send(text_data=json.dumps({'type': message_id}))

    def handle_command_started(self, wakeword_name):
        super().handle_command_started()
        thr = threading.Thread(target=self.send_command_to_avs)
        thr.start()
github lino-framework / lino / lino / modlib / notify / consumers2.py View on Github external
import json

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer


class LinoConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()
        if self.scope.get('user', False):
            username = self.scope["user"].username
            async_to_sync(self.channel_layer.group_add)(username, self.channel_name)

    def disconnect(self, close_code):
        pass

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        self.send(text_data=json.dumps({
            'message': message
        }))
github welliamcao / OpsManage / apps / cicd / consumers.py View on Github external
import json, time, ast, uuid
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from dao.cicd import AppsManage
from libs.ansible.runner import ANSRunner
from utils.logger import logger
from cicd.models import *
from dao.redisdb import DsRedis
from service.cicd.deploy import DeployRunner

def format_time(seconds):
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)  
    return "%02d:%02d:%02d" % (h, m, s)  

class AppsDeploy(WebsocketConsumer):
    def __init__(self, *args, **kwargs):
        super(AppsDeploy, self).__init__(*args, **kwargs) 
        self.stime = int(time.time())  
    
  
    def connect(self):
        self.project = self.get_apps(self.scope['url_route']['kwargs']['id'])
        
        if self.project:
            self.group_name = self.scope['url_route']['kwargs']['group_name']
            
            async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name)
 
            self.accept()            
        else:
            self.close()
github pythonzm / Ops / projs / utils / deploy_websocket.py View on Github external
import json
from collections import deque
from django.conf import settings
from projs.tasks import deploy_log
from conf.logger import deploy_logger
from projs.models import ProjectConfig
from utils.db.redis_ops import RedisOps
from projs.utils.git_tools import GitTools
from projs.utils.svn_tools import SVNTools
from ansible.plugins.callback import CallbackBase
from task.utils import ansible_api_v2, gen_resource
from channels.generic.websocket import WebsocketConsumer
from projs.utils.deploy_notice import deploy_mail, deploy_wx


class DeployConsumer(WebsocketConsumer):

    def __init__(self, *args, **kwargs):
        super(DeployConsumer, self).__init__(*args, **kwargs)
        self.redis_instance = RedisOps(settings.REDIS_HOST, settings.REDIS_PORT, 5)
        self.deploy_results = []
        self.host_fail = []
        self.config = None
        self.d_type = None
        self.release_name = None
        self.release_desc = None
        self.host_list = None
        self.branch_tag = None

    def connect(self):
        self.accept()
github MrNaif2018 / bitcart / gui / consumers.py View on Github external
#pylint: disable=no-member
from channels.generic.websocket import WebsocketConsumer, SyncConsumer
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from django.shortcuts import render, get_object_or_404, redirect, reverse
import urllib
from . import models
import json
import time


class InvoiceConsumer(WebsocketConsumer):
    def connect(self):
        self.invoice_id = self.scope["url_route"]["kwargs"]["invoice"]
        self.invoice = get_object_or_404(models.Invoice, id=self.invoice_id)
        async_to_sync(self.channel_layer.group_add)(
            self.invoice_id, self.channel_name)
        self.accept()

    def disconnect(self, close_code):
        async_to_sync(self.channel_layer.group_discard)(
            self.invoice_id, self.channel_name)

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        self.send(text_data=json.dumps({