Last active
December 19, 2016 14:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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