本文整理汇总了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)})
示例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)
示例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)})
示例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})
示例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)})
示例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.'})}
)
示例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'}
)
示例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)
})
})
示例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'})}
)
示例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'})}
)
示例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})}
)
示例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'})})
示例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,
})
})
示例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'})}
)
示例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)})