本文整理汇总了Python中channels.layers.get_channel_layer方法的典型用法代码示例。如果您正苦于以下问题:Python layers.get_channel_layer方法的具体用法?Python layers.get_channel_layer怎么用?Python layers.get_channel_layer使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类channels.layers
的用法示例。
在下文中一共展示了layers.get_channel_layer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_saves_reply_channel
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def test_saves_reply_channel(self):
async with Communicator() as communicator:
user = await AsyncUserFactory()
communicator.scope['user'] = user
await communicator.connect()
subscription = (await get_subscription(user=user))[0]
assert subscription.reply_channel is not None
await get_channel_layer().send(
subscription.reply_channel, {
'type': 'message.send',
'text': json.dumps({
'message': 'hey! whaatsup?',
}),
}
)
response = await communicator.receive_json_from()
assert response == {'message': 'hey! whaatsup?'}
示例2: taillog
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def taillog(request, hostname, port, username, password, private, tail):
"""
执行 tail log 接口
"""
channel_layer = get_channel_layer()
user = request.user.username
os.environ["".format(user)] = "true"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if password:
ssh.connect(hostname=hostname, port=port, username=username, password=decrypt_p(password))
else:
pkey = paramiko.RSAKey.from_private_key_file("{0}".format(private))
ssh.connect(hostname=hostname, port=port, username=username, pkey=pkey)
cmd = "tail " + tail
stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True)
for line in iter(stdout.readline, ""):
if os.environ.get("".format(user)) == 'false':
break
result = {"status": 0, 'data': line}
result_all = json.dumps(result)
async_to_sync(channel_layer.group_send)(user, {"type": "user.message", 'text': result_all})
示例3: push_update
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def push_update(task_id):
if WEBSOCKETS_AVAILABLE:
try:
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
task_id,
{'type': 'update_task_progress', 'data': {**Progress(task_id).get_info()}}
)
except AttributeError: # No channel layer to send to, so ignore it
pass
else:
logger.info(
'Tried to use websocket progress bar, but dependencies were not installed / configured. '
'Use pip install celery-progress[websockets] and setup channels to enable this feature.'
'See: https://channels.readthedocs.io/en/latest/ for more details.'
)
示例4: _send_to_users
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def _send_to_users(self, qs_users: QuerySet, message_obj: ChannelMessage):
"""
Send the message to the users returned by the specified Django query set.
This is an async method made private for calling it from the sync public method.
:param qs_users: Django query set returning User models. Pk field will be requested via values_list(..).
:param message_obj: Message to send.
:return:
"""
connected_user_ids = self.get_connected_users()
if not connected_user_ids:
return
# A workaround for "connection already closed" problem.
# Looks like this code is being executed in a way that
# the "connection" object it accesses is re-used for a long time and appears broken after some long delay.
connection.close()
layer = get_channel_layer() # type: RedisChannelLayer
msg = {'type': 'send_to_client', 'message': message_obj.to_dict()}
coros = list()
for user_id in qs_users.filter(pk__in=connected_user_ids).values_list('pk', flat=True):
send_to_user_coro = layer.group_send(self.user_id_to_group_name(user_id), msg)
coros.append(send_to_user_coro)
await asyncio.gather(*coros)
示例5: test_poll_observer
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def test_poll_observer():
main = ApplicationCommunicator(
MainConsumer, {'type': 'channel', 'channel': CHANNEL_MAIN}
)
await main.send_input({'type': TYPE_POLL, 'observer': 'test', 'interval': 2})
channel_layer = get_channel_layer()
# Nothing should be received in the first second.
with pytest.raises(asyncio.TimeoutError):
async with async_timeout.timeout(1):
await channel_layer.receive(CHANNEL_WORKER)
assert False
# Then after another second we should get a notification.
async with async_timeout.timeout(2):
notify = await channel_layer.receive(CHANNEL_WORKER)
assert notify['type'] == TYPE_EVALUATE
assert notify['observer'] == 'test'
示例6: send_state_event
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def send_state_event(state: Dict[str, Any]) -> None:
"""Sends the given dictionary as a state update to all connected clients."""
data = {
"type": "state_update",
"state": state,
}
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)("state", data)
示例7: send_event
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def send_event(message):
"""Construct a Channels event packet with the given message.
:param message: The message to send to the manager workers.
"""
packet = {
"type": "control_event", # This is used as the method name in the consumer.
"content": message,
}
await get_channel_layer().send(state.MANAGER_CONTROL_CHANNEL, packet)
示例8: run_consumer
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def run_consumer(timeout=None, dry_run=False):
"""Run the consumer until it finishes processing.
:param timeout: Set maximum execution time before cancellation, or
``None`` (default) for unlimited.
:param dry_run: If ``True``, don't actually dispatch messages, just
dequeue them. Defaults to ``False``.
"""
channel = state.MANAGER_CONTROL_CHANNEL
scope = {
"type": "control_event",
"channel": channel,
}
app = ApplicationCommunicator(ManagerConsumer, scope)
channel_layer = get_channel_layer()
async def _consume_loop():
"""Run a loop to consume messages off the channels layer."""
while True:
message = await channel_layer.receive(channel)
if dry_run:
continue
if message.get("type", {}) == "_resolwe_manager_quit":
break
message.update(scope)
await app.send_input(message)
if timeout is None:
await _consume_loop()
try:
# A further grace period to catch late messages.
async with async_timeout.timeout(timeout or 1):
await _consume_loop()
except asyncio.TimeoutError:
pass
await app.wait()
# Shouldn't flush channels here in case there are more processes
# using the same Redis, since flushing is global.
示例9: exit_consumer
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def exit_consumer():
"""Cause the synchronous consumer to exit cleanly."""
packet = {
"type": "_resolwe_manager_quit",
}
await get_channel_layer().send(state.MANAGER_CONTROL_CHANNEL, packet)
示例10: data_post_delete_handler
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def data_post_delete_handler(sender, instance: Data, using, **kwargs):
"""Remove files referenced by deleted object."""
channel_layer = get_channel_layer()
channel_data = {"type": TYPE_STORAGE_CLEANUP_RUN}
try:
if instance.location_id is not None:
channel_data["file_storage_id"] = instance.location_id
async_to_sync(channel_layer.send)(CHANNEL_STORAGE_CLEANUP_WORKER, channel_data)
except ChannelFull:
logger.warning("Cannot trigger storage manager run because channel is full.",)
示例11: handle
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def handle(self, *args, **options):
"""Command handle."""
channel_layer = get_channel_layer()
try:
async_to_sync(channel_layer.send)(
CHANNEL_STORAGE_MANAGER_WORKER, {"type": TYPE_STORAGE_MANAGER_RUN,},
)
except ChannelFull:
logger.warning(
"Cannot trigger storage manager run because channel is full.",
)
示例12: push
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def push(username, event):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
username,
{
"type": "push.message",
"event": event
}
)
示例13: notify_ws_clients
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def notify_ws_clients(self):
"""
Inform client there is a new message.
"""
notification = {
'type': 'recieve_group_message',
'message': '{}'.format(self.id)
}
channel_layer = get_channel_layer()
print("user.id {}".format(self.user.id))
print("user.id {}".format(self.recipient.id))
async_to_sync(channel_layer.group_send)("{}".format(self.user.id), notification)
async_to_sync(channel_layer.group_send)("{}".format(self.recipient.id), notification)
示例14: handle
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def handle(self, signal, *args, **kwargs):
message = self.serialize(signal, *args, **kwargs)
channel_layer = get_channel_layer()
for group_name in self.group_names_for_signal(*args, message=message, **kwargs):
async_to_sync(channel_layer.group_send)(group_name, message)
示例15: send_messages
# 需要导入模块: from channels import layers [as 别名]
# 或者: from channels.layers import get_channel_layer [as 别名]
def send_messages(
self, instance: Model, group_names: Set[str], action: Action, **kwargs
):
if not group_names:
return
message = self.serialize(instance, action, **kwargs)
channel_layer = get_channel_layer()
for group_name in group_names:
async_to_sync(channel_layer.group_send)(group_name, message)