Python channels.layers.get_channel_layer() Examples

The following are 30 code examples of channels.layers.get_channel_layer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module channels.layers , or try the search function .
Example #1
Source File: websockets.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 7 votes vote down vote up
def _send_to_users(self, qs_users: QuerySet, message_obj: ChannelMessage):
        """
        Send the message to the users returned by the specified Django query set.

        This is an async method made private for calling it from the sync public method.
        :param qs_users: Django query set returning User models. Pk field will be requested via values_list(..).
        :param message_obj: Message to send.
        :return:
        """
        connected_user_ids = self.get_connected_users()
        if not connected_user_ids:
            return

        # A workaround for "connection already closed" problem.
        # Looks like this code is being executed in a way that
        # the "connection" object it accesses is re-used for a long time and appears broken after some long delay.
        connection.close()

        layer = get_channel_layer()  # type: RedisChannelLayer
        msg = {'type': 'send_to_client', 'message': message_obj.to_dict()}
        coros = list()
        for user_id in qs_users.filter(pk__in=connected_user_ids).values_list('pk', flat=True):
            send_to_user_coro = layer.group_send(self.user_id_to_group_name(user_id), msg)
            coros.append(send_to_user_coro)
        await asyncio.gather(*coros) 
Example #2
Source File: test_consumers.py    From karrot-backend with GNU Affero General Public License v3.0 7 votes vote down vote up
def test_saves_reply_channel(self):
        async with Communicator() as communicator:
            user = await AsyncUserFactory()
            communicator.scope['user'] = user
            await communicator.connect()
            subscription = (await get_subscription(user=user))[0]
            assert subscription.reply_channel is not None
            await get_channel_layer().send(
                subscription.reply_channel, {
                    'type': 'message.send',
                    'text': json.dumps({
                        'message': 'hey! whaatsup?',
                    }),
                }
            )
            response = await communicator.receive_json_from()
            assert response == {'message': 'hey! whaatsup?'} 
Example #3
Source File: test_consumers.py    From django-rest-framework-reactive with Apache License 2.0 6 votes vote down vote up
def test_poll_observer():
    main = ApplicationCommunicator(
        MainConsumer, {'type': 'channel', 'channel': CHANNEL_MAIN}
    )
    await main.send_input({'type': TYPE_POLL, 'observer': 'test', 'interval': 2})
    channel_layer = get_channel_layer()

    # Nothing should be received in the first second.
    with pytest.raises(asyncio.TimeoutError):
        async with async_timeout.timeout(1):
            await channel_layer.receive(CHANNEL_WORKER)
            assert False

    # Then after another second we should get a notification.
    async with async_timeout.timeout(2):
        notify = await channel_layer.receive(CHANNEL_WORKER)
        assert notify['type'] == TYPE_EVALUATE
        assert notify['observer'] == 'test' 
Example #4
Source File: backend.py    From celery-progress with MIT License 6 votes vote down vote up
def push_update(task_id):
        if WEBSOCKETS_AVAILABLE:
            try:
                channel_layer = get_channel_layer()
                async_to_sync(channel_layer.group_send)(
                    task_id,
                    {'type': 'update_task_progress', 'data': {**Progress(task_id).get_info()}}
                )
            except AttributeError:  # No channel layer to send to, so ignore it
                pass
        else:
            logger.info(
                'Tried to use websocket progress bar, but dependencies were not installed / configured. '
                'Use pip install celery-progress[websockets] and setup channels to enable this feature.'
                'See: https://channels.readthedocs.io/en/latest/ for more details.'
            ) 
Example #5
Source File: utils.py    From ChatXChannels with MIT License 6 votes vote down vote up
def trigger_welcome_message(sender_id, receiver_id):
    data = {
        "type": "welcome_message",
        "message": "Hello there!",
        "sender_id": sender_id,
        "receiver_id": receiver_id,
        "timeout": 45
    }
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.send)('task', data) 
Example #6
Source File: views.py    From chain with Apache License 2.0 6 votes vote down vote up
def taillog(request, hostname, port, username, password, private, tail):
    """
    执行 tail log 接口
    """
    channel_layer = get_channel_layer()
    user = request.user.username
    os.environ["".format(user)] = "true"
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    if password:
        ssh.connect(hostname=hostname, port=port, username=username, password=decrypt_p(password))
    else:
        pkey = paramiko.RSAKey.from_private_key_file("{0}".format(private))
        ssh.connect(hostname=hostname, port=port, username=username, pkey=pkey)
    cmd = "tail " + tail
    stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True)
    for line in iter(stdout.readline, ""):
        if os.environ.get("".format(user)) == 'false':
            break
        result = {"status": 0, 'data': line}
        result_all = json.dumps(result)
        async_to_sync(channel_layer.group_send)(user, {"type": "user.message", 'text': result_all}) 
Example #7
Source File: channels.py    From TheSpaghettiDetective with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_msg_to_printer(printer_id, msg_dict):
    msg_dict.update({'type': 'printer.message'})    # mapped to -> printer_message in consumer
    layer = get_channel_layer()
    async_to_sync(layer.group_send)(
        octo_group_name(printer_id),
        msg_dict,
    ) 
Example #8
Source File: web.py    From ika with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.channel_layer = get_channel_layer()
        asyncio.ensure_future(self.__loop()) 
Example #9
Source File: channels.py    From TheSpaghettiDetective with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_message_to_web(printer_id, msg_dict):
    msg_dict.update({'type': 'web.message'})    # mapped to -> web_message in consumer
    layer = get_channel_layer()
    async_to_sync(layer.group_send)(
        web_group_name(printer_id),
        msg_dict,
    ) 
Example #10
Source File: channels.py    From TheSpaghettiDetective with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_status_to_web(printer_id):
    layer = get_channel_layer()
    async_to_sync(layer.group_send)(
        web_group_name(printer_id),
        {
            'type': 'printer.status',         # mapped to -> printer_status in consumer
        }
    ) 
Example #11
Source File: utils.py    From ChatXChannels with MIT License 5 votes vote down vote up
def broadcast_msg_to_chat(msg, group_name, user='admin', event_type='broadcast_message'):
    channel_layer = get_channel_layer()
    actual_message = json.dumps({'msg': msg, 'user': user})
    broadcast_data = {
        'type': event_type,
        'message': actual_message
    }
    async_to_sync(channel_layer.group_send)(group_name, broadcast_data) 
Example #12
Source File: channels.py    From TheSpaghettiDetective with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_janus_to_web(printer_id, msg):
    layer = get_channel_layer()
    async_to_sync(layer.group_send)(
        janus_web_group_name(printer_id),
        {
            'type': 'janus.message',         # mapped to -> janus_message in consumer
            'msg': msg,
        }
    ) 
Example #13
Source File: signals.py    From timestrap with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def sync_clients_save(sender, instance, **kwargs):
    """
    Use django channels to sync all our current clients.
    """
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "sync_clients", {"type": "sync_clients.save", "model": sender.__name__}
    ) 
Example #14
Source File: consumers.py    From django-plotly-dash with MIT License 5 votes vote down vote up
def async_send_to_pipe_channel(channel_name,
                                     label,
                                     value):
    'Send message asynchronously through pipe to client component'
    pcn = _form_pipe_channel_name(channel_name)

    channel_layer = get_channel_layer()
    await channel_layer.group_send(pcn,
                                   {"type":"pipe.value",
                                    "label":label,
                                    "value":value}) 
Example #15
Source File: mixins.py    From django-knocker with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_knock(self, signal_type, created=False):
        """
        Send the knock in the associated channels Group
        """
        knock = self.as_knock(signal_type, created)
        if knock:
            channel_layer = get_channel_layer()
            group = 'knocker-%s' % knock['language']
            async_to_sync(channel_layer.group_send)(group, {
                'type': 'knocker.saved',
                'message': json.dumps(knock)
            }) 
Example #16
Source File: state_handler.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def send_state_event(state: Dict[str, Any]) -> None:
    """Sends the given dictionary as a state update to all connected clients."""
    data = {
        "type": "state_update",
        "state": state,
    }
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)("state", data) 
Example #17
Source File: signals.py    From timestrap with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def sync_clients_delete(sender, instance, **kwargs):
    """
    Use django channels to sync all our current clients.
    """
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "sync_clients", {"type": "sync_clients.delete", "model": sender.__name__}
    ) 
Example #18
Source File: signals.py    From django-rest-framework-reactive with Apache License 2.0 5 votes vote down vote up
def notify_observers(table, kind, primary_key=None):
    """Transmit ORM table change notification.

    :param table: Name of the table that has changed
    :param kind: Change type
    :param primary_key: Primary key of the affected instance
    """

    if IN_MIGRATIONS:
        return

    # Don't propagate events when there are no observers to receive them.
    if not Observer.objects.filter(dependencies__table=table).exists():
        return

    def handler():
        """Send a notification to the given channel."""
        try:
            async_to_sync(get_channel_layer().send)(
                CHANNEL_MAIN,
                {
                    'type': TYPE_ORM_NOTIFY,
                    'table': table,
                    'kind': kind,
                    'primary_key': str(primary_key),
                },
            )
        except ChannelFull:
            logger.exception("Unable to notify workers.")

    batcher = PrioritizedBatcher.global_instance()
    if batcher.is_started:
        # If a batch is open, queue the send via the batcher.
        batcher.add(
            'rest_framework_reactive', handler, group_by=(table, kind, primary_key)
        )
    else:
        # If no batch is open, invoke immediately.
        handler() 
Example #19
Source File: websockets.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_to_user(self, user_id, message_obj: ChannelMessage):
        """
        Send the message to the specified user.
        :param user_id: ID of the user.
        :param message_obj: Message to send.
        :return:
        """
        layer = get_channel_layer()  # type: RedisChannelLayer
        async_to_sync(layer.group_send)(self.user_id_to_group_name(user_id),
                                        {'type': 'send_to_client', 'message': message_obj.to_dict()}) 
Example #20
Source File: websockets.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_to_all_users(self, message_obj: ChannelMessage):
        """
        Send the message to all connected users.
        Each authenticated user is added to a special ALL group and this method sends the message into this group.
        :param message_obj:
        :return:
        """
        layer = get_channel_layer()  # type: RedisChannelLayer
        async_to_sync(layer.group_send)(ALL, {'type': 'send_to_client', 'message': message_obj.to_dict()}) 
Example #21
Source File: notifiers.py    From lego with MIT License 5 votes vote down vote up
def notify_group(group, message):
    """
    Dumps the message to JSON and sends it to the specified channel.

    :param group: str
    :param message: dict
    """
    channel_layer = get_channel_layer()
    payload = json.dumps(camelize(message))
    return AsyncToSync(channel_layer.group_send)(
        group, {"type": "notification.message", "text": payload}
    ) 
Example #22
Source File: model_observer.py    From djangochannelsrestframework with MIT License 5 votes vote down vote up
def send_messages(
        self, instance: Model, group_names: Set[str], action: Action, **kwargs
    ):
        if not group_names:
            return
        message = self.serialize(instance, action, **kwargs)
        channel_layer = get_channel_layer()
        for group_name in group_names:
            async_to_sync(channel_layer.group_send)(group_name, message) 
Example #23
Source File: observer.py    From djangochannelsrestframework with MIT License 5 votes vote down vote up
def handle(self, signal, *args, **kwargs):
        message = self.serialize(signal, *args, **kwargs)
        channel_layer = get_channel_layer()
        for group_name in self.group_names_for_signal(*args, message=message, **kwargs):
            async_to_sync(channel_layer.group_send)(group_name, message) 
Example #24
Source File: models.py    From django-channels-chat with MIT License 5 votes vote down vote up
def notify_ws_clients(self):
        """
        Inform client there is a new message.
        """
        notification = {
            'type': 'recieve_group_message',
            'message': '{}'.format(self.id)
        }

        channel_layer = get_channel_layer()
        print("user.id {}".format(self.user.id))
        print("user.id {}".format(self.recipient.id))

        async_to_sync(channel_layer.group_send)("{}".format(self.user.id), notification)
        async_to_sync(channel_layer.group_send)("{}".format(self.recipient.id), notification) 
Example #25
Source File: consumers.py    From onehome-server with MIT License 5 votes vote down vote up
def push(username, event):
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        username,
        {
            "type": "push.message",
            "event": event
        }
    ) 
Example #26
Source File: runstoragemanager.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def handle(self, *args, **options):
        """Command handle."""
        channel_layer = get_channel_layer()
        try:
            async_to_sync(channel_layer.send)(
                CHANNEL_STORAGE_MANAGER_WORKER, {"type": TYPE_STORAGE_MANAGER_RUN,},
            )
        except ChannelFull:
            logger.warning(
                "Cannot trigger storage manager run because channel is full.",
            ) 
Example #27
Source File: signals.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def data_post_delete_handler(sender, instance: Data, using, **kwargs):
    """Remove files referenced by deleted object."""
    channel_layer = get_channel_layer()
    channel_data = {"type": TYPE_STORAGE_CLEANUP_RUN}
    try:
        if instance.location_id is not None:
            channel_data["file_storage_id"] = instance.location_id
        async_to_sync(channel_layer.send)(CHANNEL_STORAGE_CLEANUP_WORKER, channel_data)
    except ChannelFull:
        logger.warning("Cannot trigger storage manager run because channel is full.",) 
Example #28
Source File: consumer.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def exit_consumer():
    """Cause the synchronous consumer to exit cleanly."""
    packet = {
        "type": "_resolwe_manager_quit",
    }
    await get_channel_layer().send(state.MANAGER_CONTROL_CHANNEL, packet) 
Example #29
Source File: consumer.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def run_consumer(timeout=None, dry_run=False):
    """Run the consumer until it finishes processing.

    :param timeout: Set maximum execution time before cancellation, or
        ``None`` (default) for unlimited.
    :param dry_run: If ``True``, don't actually dispatch messages, just
        dequeue them. Defaults to ``False``.
    """
    channel = state.MANAGER_CONTROL_CHANNEL
    scope = {
        "type": "control_event",
        "channel": channel,
    }

    app = ApplicationCommunicator(ManagerConsumer, scope)

    channel_layer = get_channel_layer()

    async def _consume_loop():
        """Run a loop to consume messages off the channels layer."""
        while True:
            message = await channel_layer.receive(channel)
            if dry_run:
                continue
            if message.get("type", {}) == "_resolwe_manager_quit":
                break
            message.update(scope)
            await app.send_input(message)

    if timeout is None:
        await _consume_loop()
    try:
        # A further grace period to catch late messages.
        async with async_timeout.timeout(timeout or 1):
            await _consume_loop()
    except asyncio.TimeoutError:
        pass

    await app.wait()
    # Shouldn't flush channels here in case there are more processes
    # using the same Redis, since flushing is global. 
Example #30
Source File: consumer.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def send_event(message):
    """Construct a Channels event packet with the given message.

    :param message: The message to send to the manager workers.
    """
    packet = {
        "type": "control_event",  # This is used as the method name in the consumer.
        "content": message,
    }
    await get_channel_layer().send(state.MANAGER_CONTROL_CHANNEL, packet)