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