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


Python Group.send方法代碼示例

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


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

示例1: send_data

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
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,代碼行數:35,代碼來源:autoupdate.py

示例2: ws_message

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
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,代碼行數:29,代碼來源:consumers.py

示例3: send_knock

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
 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,代碼行數:10,代碼來源:mixins.py

示例4: chat_consumer

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
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,代碼行數:12,代碼來源:consumers.py

示例5: GroupStreamer

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
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,代碼行數:13,代碼來源:temp.py

示例6: connect_wait_for_session

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
def connect_wait_for_session(message, pre_create_id):
    group = Group(channels_create_session_group_name(pre_create_id))
    group.add(message.reply_channel)

    # in case message was sent before this web socket connects
    if Session.objects.filter(_pre_create_id=pre_create_id):
        group.send(
        {'text': json.dumps(
            {'status': 'ready'})}
        )
    elif FailedSessionCreation.objects.filter(
        pre_create_id=pre_create_id
    ).exists():
        group.send(
            {'text': json.dumps(
                {'error': 'Failed to create session. Check the server logs.'})}
        )
開發者ID:jpg75,項目名稱:otree-core,代碼行數:19,代碼來源:consumers.py

示例7: notify_subscribers

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
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,代碼行數:20,代碼來源:subscribers.py

示例8: data_entry_receive

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
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,代碼行數:20,代碼來源:consumers.py

示例9: create_session

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
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,代碼行數:21,代碼來源:consumers.py

示例10: create_session

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
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,代碼行數:45,代碼來源:consumers.py

示例11: connect_wait_for_session

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
def connect_wait_for_session(message, pre_create_id):
    group = Group(channels_create_session_group_name(pre_create_id))
    group.add(message.reply_channel)

    # in case message was sent before this web socket connects
    if Session.objects.filter(_pre_create_id=pre_create_id, ready=True):
        group.send(
            {'text': json.dumps(
                {'status': 'ready'})}
        )
    else:
        failure = FailedSessionCreation.objects.filter(
            pre_create_id=pre_create_id
        ).first()
        if failure:
            group.send(
                {'text': json.dumps(
                    {'error': failure.message,
                     'traceback': failure.traceback})}
            )
開發者ID:goakichang,項目名稱:otree-core,代碼行數:22,代碼來源:consumers.py

示例12: create_session

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
def create_session(message):

    group = Group(message['channels_group_name'])

    kwargs = message['kwargs']
    try:
        otree.session.create_session(**kwargs)
    except Exception as e:
        error_message = 'Failed to create session: "{}" - Check the server logs'.format(
                    str(e))
        group.send(
            {'text': json.dumps(
                {'error': error_message})}
        )
        FailedSessionCreation(
            pre_create_id=kwargs['_pre_create_id'],
            message=error_message[:FAILURE_MESSAGE_MAX_LENGTH]
        ).save()
        raise
    group.send({'text': json.dumps({'status': 'ready'})})
開發者ID:BertrandBordage,項目名稱:otree-core,代碼行數:22,代碼來源:consumers.py

示例13: send_game_list

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
def send_game_list(channel):
    games = Game.objects.filter(status__in=['Created', 'Started'])
    game_list = []
    for game in games:
        state = cache.get(GAME + str(game.id), new_state())
        game_list.append({
            'id': game.id,
            'name': game.name,
            'level': game.level,
            'players_num': game.players_num,
            'players': state['players']
        })

    if isinstance(channel, str):
        channel = Group(channel)

    channel.send({
        'text': json.dumps({
            'game_list': game_list,
        })
    })
開發者ID:UncleVasya,項目名稱:mafia-modern,代碼行數:23,代碼來源:consumers.py

示例14: create_session

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
def create_session(message):
    group = Group(message['channels_group_name'])

    kwargs = message['kwargs']

    # because it's launched through web UI
    kwargs['honor_browser_bots_config'] = True
    try:
        otree.session.create_session(**kwargs)
    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:mattboehm,項目名稱:otree-core,代碼行數:40,代碼來源:consumers.py

示例15: ws_disconnect

# 需要導入模塊: from channels import Group [as 別名]
# 或者: from channels.Group import send [as 別名]
def ws_disconnect(message, room):
    g = Group('chat:{}'.format(room))
    g.discard(message.reply_channel)
    data = {'text': 'A user disconnected', 'type': 'log'}
    g.send({'text': json.dumps(data)})
開發者ID:mediainteractiva,項目名稱:chan,代碼行數:7,代碼來源:consumers.py


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