當前位置: 首頁>>代碼示例>>Python>>正文


Python channels.Group類代碼示例

本文整理匯總了Python中channels.Group的典型用法代碼示例。如果您正苦於以下問題:Python Group類的具體用法?Python Group怎麽用?Python Group使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Group類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: send_data

def send_data(message):
    """
    Informs all users about changed data.

    The argument message has to be a dict with the keywords collection_string
    (string), pk (positive integer), id_deleted (boolean) and dispatch_uid
    (string).
    """
    for access_permissions in BaseAccessPermissions.get_all():
        if access_permissions.get_dispatch_uid() == message['dispatch_uid']:
            break
    else:
        raise ValueError('Invalid message. A valid dispatch_uid is missing.')

    if not message['is_deleted']:
        Model = get_model_from_collection_string(message['collection_string'])
        instance = Model.objects.get(pk=message['pk'])
        full_data = access_permissions.get_full_data(instance)

    # Loop over all logged in users and the anonymous user.
    for user in itertools.chain(get_logged_in_users(), [AnonymousUser()]):
        channel = Group('user-{}'.format(user.id))
        output = {
            'collection': message['collection_string'],
            'id': instance.get_rest_pk(),
            'action': 'deleted' if message['is_deleted'] else 'changed'}
        if not message['is_deleted']:
            data = access_permissions.get_restricted_data(full_data, user)
            if data is None:
                # There are no data for the user so he can't see the object. Skip him.
                continue
            output['data'] = data
        channel.send({'text': json.dumps(output)})
開發者ID:muguli22,項目名稱:OpenSlides,代碼行數:33,代碼來源:autoupdate.py

示例2: ws_message

def ws_message(message):
    '''Send a message via web sockets.  Currently uses a group identified by
    notify-username.  When a volume export form submission is received,
    the message is handed off to the volume-export channel, which is handled
    by :mod:`readux.books.consumers`.  Otherwise, messages are routed to the
    user notification channel.'''
    # does this really need to be a group? can we just use the reply channel?
    notify = Group("notify-%s" % message.user.username)
    # check for volume export data (form submission)
    if 'volume_export' in message.content['text']:
        data = json.loads(message.content['text'])
        # parse_qs returns values as lists
        formdata = dict((key, val[0])
                        for key, val in parse_qs(data['volume_export']).iteritems())
        # breaking changes as of channels 1.0
        # need to specify immediately=True to send messages before the consumer completes to the end
        Channel('volume-export').send({
            # has to be json serializable, so send username rather than user
            'user': message.user.username,
            'formdata': formdata,
            # fixme: why is reply channel not automatically set?
            # 'reply_channel': message.reply_channel
        }, immediately=True)
    else:
        notify.send({
            "text": "%s" % message.content['text'],
        }, immediately=True)
開發者ID:emory-libraries,項目名稱:readux,代碼行數:27,代碼來源:consumers.py

示例3: connect_wait_page

def connect_wait_page(message, params):
    session_pk, page_index, model_name, model_pk = params.split(',')
    session_pk = int(session_pk)
    page_index = int(page_index)
    model_pk = int(model_pk)

    group_name = channels_wait_page_group_name(
        session_pk, page_index, model_name, model_pk
    )
    group = Group(group_name)
    group.add(message.reply_channel)

    # in case message was sent before this web socket connects

    if model_name == 'group':
        ready = CompletedGroupWaitPage.objects.filter(
            page_index=page_index,
            group_pk=model_pk,
            session_pk=session_pk,
            after_all_players_arrive_run=True).exists()
    else: # subsession
        ready = CompletedSubsessionWaitPage.objects.filter(
            page_index=page_index,
            session_pk=session_pk,
            after_all_players_arrive_run=True).exists()
    if ready:
        message.reply_channel.send(
            {'text': json.dumps(
                {'status': 'ready'})})
開發者ID:jpg75,項目名稱:otree-core,代碼行數:29,代碼來源:consumers.py

示例4: ws_disconnect

def ws_disconnect(message):
    """
    Channels connection close.
    Deregister the client
    """
    language = message.channel_session['knocker']
    gr = Group('knocker-{0}'.format(language))
    gr.discard(message.reply_channel)
開發者ID:adamchainz,項目名稱:django-knocker,代碼行數:8,代碼來源:consumers.py

示例5: send_knock

 def send_knock(self, created=False):
     """
     Send the knock in the associated channels Group
     """
     knock = self.as_knock(created)
     if knock:
         gr = Group('knocker-{0}'.format(knock['language']))
         gr.send({'text': json.dumps(knock)})
開發者ID:nephila,項目名稱:django-knocker,代碼行數:8,代碼來源:mixins.py

示例6: ws_connect

def ws_connect(message):
    """
    Channels connection setup.
    Register the current client on the related Group according to the language
    """
    prefix, language = message['path'].strip('/').split('/')
    gr = Group('knocker-{0}'.format(language))
    gr.add(message.reply_channel)
    message.channel_session['knocker'] = language
開發者ID:adamchainz,項目名稱:django-knocker,代碼行數:9,代碼來源:consumers.py

示例7: chat_consumer

def chat_consumer(message):
    room = message.content['room']
    text = message.content['message']
    username = message.content['username']
    ChatMessage.objects.create(room=room, message=message)

    data = json.dumps({'message': text, 'username': username})

    group = Group('chat-%s' % room)
    group.send({'text': data})
開發者ID:bionikspoon,項目名稱:django_channels_chat,代碼行數:10,代碼來源:consumers.py

示例8: disconnect_wait_page

def disconnect_wait_page(message, params):
    app_label, page_index, model_name, model_pk = params.split(',')
    page_index = int(page_index)
    model_pk = int(model_pk)

    group_name = channels_wait_page_group_name(
        app_label, page_index, model_name, model_pk
    )
    group = Group(group_name)
    group.discard(message.reply_channel)
開發者ID:jpg75,項目名稱:otree-core,代碼行數:10,代碼來源:consumers.py

示例9: GroupStreamer

class GroupStreamer(Streamer):
    def __init__(self):
        pass

    def prepare(self):
        from django.conf import settings
        from channels import Group
        self.group = Group(settings.TEMP_GROUP_NAME)

    def __call__(self, temperature):
        self.group.send({'text': self.format(temperature)})
開發者ID:sindrig,項目名稱:PiTemp,代碼行數:11,代碼來源:temp.py

示例10: sign_in

 def sign_in(self, request, data, *args, **kwargs):
     serializer = IsAuthenticatedSerializer(data=data)
     serializer.is_valid(raise_exception=True)
     band_id = kwargs.get("band_id")
     user = self.check_chat_perms(serializer, band_id)
     if user is not None:
         request.channel_session["user"] = user.id
         group = Group(self.CHAT_GROUP_TEMPLATE % band_id)
         group.add(request.reply_channel)
         messages = Message.objects.select_related("author").filter(band_id=band_id)[: self.MESSAGES_COUNT][::-1]
         self.route_send(request.reply_channel, MessagesSerializer({"messages": messages}).data)
     else:
         raise PermissionDenied
開發者ID:YetAnotherTeam,項目名稱:jatumba-backend,代碼行數:13,代碼來源:web_socket.py

示例11: connect_auto_advance

def connect_auto_advance(message, params):
    participant_code, page_index = params.split(',')
    page_index = int(page_index)

    group = Group('auto-advance-{}'.format(participant_code))
    group.add(message.reply_channel)

    # in case message was sent before this web socket connects
    participant = Participant.objects.get(code=participant_code)
    if participant._index_in_pages > page_index:
        message.reply_channel.send(
            {'text': json.dumps(
                {'new_index_in_pages': participant._index_in_pages})}
        )
開發者ID:KeyangRU,項目名稱:otree-core,代碼行數:14,代碼來源:consumers.py

示例12: data_entry_receive

def data_entry_receive(message, game_id):
    game = Game.objects.get(pk=game_id)
    group = Group('data-entry-%s' % game_id)
    data = json.loads(message['text'])
    round_score, created = RoundScore.objects.get_or_create(
        score__game=game,
        score_id=data['score'],
        round_number=data['round'],
        defaults={'value': data['value']},
    )
    if not created:
        round_score.value = data['value']
        round_score.save()
    group.send({
        'text': json.dumps({
            'data': _round_scores_for_game(game)
        })
    })
開發者ID:mjtamlyn,項目名稱:channels-scoring,代碼行數:18,代碼來源:consumers.py

示例13: notify_subscribers

def notify_subscribers(notifications, key):
    """
    Notify all open channels about new notifications
    """

    logger.debug("Broadcasting to subscribers")

    notification_type_ids = models.NotificationType.objects.values('key').filter(key=key)

    for notification_type in notification_type_ids:
        g = Group(
            settings.NOTIFICATION_CHANNEL.format(
                notification_key=notification_type['key']
            )
        )
        g.send(
            {'text': 'new-notification'}
        )
開發者ID:benjaoming,項目名稱:django-nyt,代碼行數:18,代碼來源:subscribers.py

示例14: create_session

def create_session(message):
    group = Group(message['channels_group_name'])

    kwargs = message['kwargs']

    try:
        session = otree.session.create_session(**kwargs)
        if message['use_browser_bots']:
            otree.bots.browser.initialize_session(
                session_pk=session.pk,
                case_number=None
            )
        session.ready_for_browser = True
        session.save()
    except Exception as e:

        # full error message is printed to console (though sometimes not?)
        error_message = 'Failed to create session: "{}"'.format(e)
        traceback_str = traceback.format_exc()
        group.send(
            {'text': json.dumps(
                {
                    'error': error_message,
                    'traceback': traceback_str,
                })}
        )
        FailedSessionCreation.objects.create(
            pre_create_id=kwargs['pre_create_id'],
            message=error_message[:FAILURE_MESSAGE_MAX_LENGTH],
            traceback=traceback_str
        )
        raise

    group.send(
        {'text': json.dumps(
            {'status': 'ready'})}
    )

    if 'room_name' in kwargs:
        Group(channel_utils.room_participants_group_name(kwargs['room_name'])).send(
            {'text': json.dumps(
                {'status': 'session_ready'})}
        )
開發者ID:oTree-org,項目名稱:otree-core,代碼行數:43,代碼來源:consumers.py

示例15: create_session

def create_session(message):

    group = Group(message['channels_group_name'])

    kwargs = message['kwargs']
    try:
        otree.session.create_session(**kwargs)
    except Exception as e:
        group.send(
            {'text': json.dumps(
                {'error': 'Failed to create session. Check the server logs.'})}
        )
        FailedSessionCreation(pre_create_id=kwargs['_pre_create_id']).save()
        raise e

    group.send(
        {'text': json.dumps(
            {'status': 'ready'})}
)
開發者ID:KeyangRU,項目名稱:otree-core,代碼行數:19,代碼來源:consumers.py


注:本文中的channels.Group類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。