3

I have an external Python script which generates JSON data every second; on the other side i have a Django application. I would like to stream that data on a webpage on my Django app. I already built a consumer with Django channels, but i don't know how to make Django have the data that i generate from the other Python script.

Here is my basic consumer:

class EchoConsumer(AsyncConsumer):
    async def websocket_connect(self, event):
        print("connected", event)


        await self.send({
            "type": "websocket.accept"
        })


    async def websocket_receive(self, event):
        print("received", event)
        # Echo the same received payload

    async def websocket_disconnect(self, event):
        print("disconnected", event)

Is there a specific way do this? Or am i supposed to use another service in the middle?Any advice is appreciated

2 Answers 2

3

You can use the channel layer that is used to connect two or more 'Consumers' together. For example you want to build a chat room application and want multiple users in a room to send messages to each other in 'Realtime' you'd have to link then up using the channels layer.

    async def start_chat(self, event):
        auth_user = self.scope['user']
        data = event['data']
        recipient_user = data['recipient']

        self.chat_room = f'thread_{self.thread.id}'

        await self.channel_layer.group_add(
            self.chat_room,
            self.channel_name
        )

    async def send_chat_message(self, event):
        message = await self.create_message_db(event.get('data'))
        message_data = MessageReadOnlySerializer(message).data

        # encoding the UUID object to json
        uid = message_data['sender']
        message_data['sender'] = json.loads(json.dumps(uid, cls=utlis.UUIDEncoder))

        await self.channel_layer.group_send(
            group=self.chat_room,
            message={
                'type': 'echo.message',
                'data': {
                    'message': message_data
                }

            }
        )

    async def echo_message(self, event):
        await self.send_json(event)

The code above is an example of how to use the channel layer. In the start_chat function, we are adding two consumers to a group this way we have established a path of communication between them so now when a consumer calls the send_chat_message it will call the echo_message function on both of the consumers.

Sign up to request clarification or add additional context in comments.

1 Comment

I did not know about this use case. This could be what i'm looking for, thank you!
0

What you could do is to pour that data to a DB model by using the @database_sync_to_async decorator. Take a look at the following example

 async def websocket_receive(self, event):
   message = await self.create_message_db(event.get('data'))

 @database_sync_to_async
  def create_message_db(self, data):
      return Message.objects.create(thread=self.thread, sender=self.scope['user'], 
             body=data['message'])

3 Comments

Hey, i considered updating it to a database, but since it's real time data and i would be uploading a lot of data every second, using a db would probably make me run into performance issues, so i can't use it for now
@Sile well then you can use the channel layer to connect two or more consumers together.
Thanks for your answer! Can you please specify a little bit more about it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.