Skip to content

Instantly share code, notes, and snippets.

@dequn

dequn/channels.py

Created Jun 30, 2018
Embed
What would you like to do?
channel layers subscribe redis and using outside of consumer
def handle(self, *args, **options):
redis = get_redis_connection()
ps = redis.pubsub()
ps.subscribe([RELAY_CONTROL_RESULT_CHANNEL])
for item in ps.listen():
if item['type'] == 'message':
data = item['data']
equipment_id, return_state = data.decode('ascii').split(':')
# equipment_id is group name
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
equipment_id,
{"type": "relay_message",
# relay_message is a function, must be defined in a consumer which in the group name of `equipment_id`
"return_state": int(return_state)
}
)
class ExampleConsumer(AsyncWebsocketConsumer):
async def connect(self):
# ...code to parse equipment_id
self.channel_layer.group_add(
equipment_id,
self.channel_name
)
# other code
async def relay_message(self, event):
return_state = event['return_state']
# other code
await self.send(text_data="some message send to client")
# other function rewrite
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.