Skip to content

Instantly share code, notes, and snippets.

@dequn
Created June 30, 2018 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dequn/c1569c38bfd95a70c4bafc24b9189360 to your computer and use it in GitHub Desktop.
Save dequn/c1569c38bfd95a70c4bafc24b9189360 to your computer and use it in GitHub Desktop.
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