How to use the channels.sessions.channel_session 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 ScanOC / trunk-player / radio / consumers.py View on Github external
@channel_session
def ws_connect(message):
    try:
        prefix, tg_type, label = message['path'].strip('/').split('/')
        if prefix != 'ws-calls':
            log.debug('invalid ws path=%s', message['path'])
            return
    except ValueError:
        log.debug('invalid ws path=%s', message['path'])
        return

    log.debug('connect %s=%s client=%s:%s', 
        tg_type, label, message['client'][0], message['client'][1])
   
    label_list = label.split('+')
    for new_label in label_list: 
        channel_name = 'livecall-{}-{}'.format(tg_type, new_label)
github jackeyGao / django-vuejs / chat / consumers.py View on Github external
@channel_session
def ws_connect(message):
    # Extract the room from the message. This expects message.path to be of the
    # form /chat/{label}/, and finds a Room if the message path is applicable,
    # and if the Room exists. Otherwise, bails (meaning this is a some othersort
    # of websocket). So, this is effectively a version of _get_object_or_404.
    try:
        prefix, label = message['path'].decode('ascii').strip('/').split('/')
        if prefix != 'chat':
            log.debug('invalid ws path=%s', message['path'])
            return
        room = Room.objects.get(label=label)
    except ValueError:
        log.debug('invalid ws path=%s', message['path'])
        return
    except Room.DoesNotExist:
        log.debug('ws room does not exist label=%s', label)
github antsmc2 / webrtc_meetings / webrtc_meetings / routing.py View on Github external
@channel_session
def ws_add(message):
    # to fix later. This implicitly assumes fix ws_url pattern
    room_id = message['path'].strip('/').split('/')[-1]
    wlogger.debug('adding %s'% room_id)
    meeting = Meeting.get_meeting(room_id) #allow ex
    Group(settings.ROOM_KEY_FORMAT % {'room_id': room_id}
          ).add(message.reply_channel)
    message.channel_session['room'] = room_id
    wlogger.debug('message from: %s, room: %s' % (message, room_id))
    message.reply_channel.send({'accept': True})
github lino-framework / lino / lino / modlib / notify / consumers.py View on Github external
    @channel_session
    @functools.wraps(func)
    def inner(message, *args, **kwargs):
        # If we didn't get a session, then we don't get a user
        if not hasattr(message, "channel_session"):
            raise ValueError("Did not see a channel session to get auth from")
        if message.channel_session is None:
            # Inner import to avoid reaching into models before load complete
            message.user = AnonymousUser()
        # Otherwise, be a bit naughty and make a fake Request with just
        # a "session" attribute (later on, perhaps refactor contrib.auth to
        # pass around session rather than request)
        else:
            fake_request = type("FakeRequest", (object,), {"session": message.channel_session})
            message.user = get_user(fake_request)
        # Run the consumer
        return func(message, *args, **kwargs)
github pixelpassion / drf-saas-starter / apps / users / consumers.py View on Github external
@channel_session
def users_ws_message(message):
    # Stick the message onto the processing queue
    Channel("chat-messages").send({
        "room": message.channel_session['room'],
        "message": message['text'],
    })
github antsmc2 / webrtc_meetings / webrtc_meetings / routing.py View on Github external
@channel_session
def ws_disconnect(message):
    group = get_group(message)
    wlogger.debug('disconnecting %s-%s' % (message.reply_channel.name,
                                           group.name))
    group.discard(message.reply_channel)
github Conchylicultor / DeepQA / chatbot_website / chatbot_interface / consumer.py View on Github external
@channel_session
def ws_disconnect(message):
    """ Called when a client disconnect
    Args:
        message (Obj): object containing the client query
    """
    clientName = message.channel_session['room']
    logger.info('Client disconnected: {}'.format(clientName))
    Group(clientName).discard(message.reply_channel)
github sourcelair-blueprints / django-channels-chat / chat / consumers.py View on Github external
@channel_session
def ws_echo(message):
    if 'username' not in message.channel_session:
        return
    room = message.channel_session['room']
    logging.info('Echoing message %s from username %s in room %s',
                 message.content['text'], message.channel_session['username'],
                 room)
    Group('chat-%s' % room).send({
        'text': json.dumps({
            'message': message.content['text'],
            'username': message.channel_session['username']
        }),
github Conchylicultor / DeepQA / chatbot_website / chatbot_interface / consumer.py View on Github external
@channel_session
def ws_receive(message):
    """ Called when a client send a message
    Args:
        message (Obj): object containing the client query
    """
    # Get client info
    clientName = message.channel_session['room']
    data = json.loads(message['text'])

    # Compute the prediction
    question = data['message']
    try:
        answer = ChatbotManager.callBot(question)
    except:  # Catching all possible mistakes
        logger.error('{}: Error with this question {}'.format(clientName, question))
        logger.error("Unexpected error:", sys.exc_info()[0])
github asyncee / django-channels-chat / src / chat_engine / engine.py View on Github external
@channel_session
def on_disconnect(message):
    Group('chat').discard(message.reply_channel)
    Group('chat').send(messages.system(
        _('User %(user)s left chat') % message.channel_session))