Skip to content

Instantly share code, notes, and snippets.

@hiway
Last active December 19, 2016 14:05
Show Gist options
  • Save hiway/4be866f636c5f5246e3d55ce66e8912f to your computer and use it in GitHub Desktop.
Save hiway/4be866f636c5f5246e3d55ce66e8912f to your computer and use it in GitHub Desktop.
Initial test - seems to work :) `from config.asgi import channel_layer` should reflect the import for your code's asgi.py
import asyncio
import traceback
from channels import Group
from config.asgi import channel_layer
class ChannelsConsumer(object):
async def long_running_operation(self, duration):
await asyncio.sleep(duration)
Group('test').send({'text': 'Hello, world!'})
async def start(self, channel_layer, channel_names):
if isinstance(channel_names, str):
channel_names = [channel_names]
while True:
channel, message = channel_layer.receive_many(channel_names,
block=False)
if channel:
print('RECV', channel, message)
# Fire off a long-running task
asyncio.ensure_future(self.long_running_operation(2))
# Continue processing other messages immediately
else:
await asyncio.sleep(0.1)
def run(self, channel_layer, channel_names):
loop = asyncio.get_event_loop()
asyncio.ensure_future(self.start(channel_layer, channel_names))
try:
loop.run_forever()
except Exception as e:
traceback.print_exc()
finally:
loop.close()
consumer = ChannelsConsumer()
consumer.run(channel_layer, 'test')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment