Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django channels between different docker containers

I'm working with django channels and I have a problem about how to deal with sending a message using channels

Context

I have 2 containers: celery-worker and api, I want to send data via websockets from celery-worker container to the browser through api container using channels, here a picture:

enter image description here

Question

Do you know how to "initialize" channels in api container and use this channels inside celery-worker container? to after in celery-worker container call only to Group('pablo').send(message) and it automatically send to the browser.

Any advice will be ok.

Note: I tried to not post code because is very extensive and maybe It would result difficult to understand the question but if you want I can post some code that you need.

like image 827
Pablo Cesar Cordova Morales Avatar asked May 18 '18 14:05

Pablo Cesar Cordova Morales


1 Answers

I have created the example (with simple tasks) that is using Celery and Django Channels 2 (github). Celery worker is sending to channel layer messages. Messages are broadcasted to clients that are connected to websocket.

On server side I have consumer:

class TasksConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        # One group name for all clients: 'tasks'
        self.group_name = 'tasks'
        await self.channel_layer.group_add(self.group_name, self.channel_name)
        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(self.group_name, self.channel_name)

    async def receive(self, text_data):
        pass

    async def task_update_message(self, event):
        # Send message to channel
        await self.send(json.dumps(event))

You can see that the group name is 'tasks'. On celery side, worker is calling:

channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)("tasks", msg)

To use channels in worker code, you need to set django settings:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings')
import django
django.setup()

Hope it helps!

like image 63
pplonski Avatar answered Nov 18 '22 02:11

pplonski