Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django channels group_send not working properly

I was trying to implement a bidding module with django-channels. Basically I broadcast any message I received from clients, and my consumer part goes as the following code snippet:

class BidderConsumer(AsyncJsonWebsocketConsumer):

    async def connect(self):
        print("Connected")
        await self.accept()
        # Add to group
        self.channel_layer.group_add("bidding", self.channel_name)
        # Add channel to group
        await self.send_json({"msg_type": "connected"})

    async def receive_json(self, content, **kwargs):
        price = int(content.get("price"))
        item_id = int(content.get("item_id"))
        print("receive price ", price)
        print("receive item_id ", item_id)
        if not price or not item_id:
            await self.send_json({"error": "invalid argument"})

        item = await get_item(item_id)
        # Update bidding price
        if price > item.price:
            item.price = price
            await save_item(item)
            # Broadcast new bidding price
            print("performing group send")
            await self.channel_layer.group_send(
                "bidding",
                {
                    "type": "update.price"
                    "price": price,
                    "item_id": item_id
                }
            )

    async def update_price(self, event):
        print("sending new price")
        await self.send_json({
            "msg_type": "update",
            "item_id": event["item_id"],
            "price": event["price"],
        })

But when I attempted to update the price from browser, the consumer could received the message from it however it could not successfully call the update_price function. (sending new price was never printed):

receive price  701
receive item_id  2
performing group send

I was just following this example: https://github.com/andrewgodwin/channels-examples/tree/master/multichat

Any advice would be greatly appreciated!

like image 365
Jiang Wenbo Avatar asked Oct 19 '25 02:10

Jiang Wenbo


1 Answers

Basically, change from this:

await self.channel_layer.group_send(
    "bidding",
    {
        "type": "update.price"
         "price": price,
         "item_id": item_id
    }
)

to this:

await self.channel_layer.group_send(
     "bidding",
     {
         "type": "update_price"
         "price": price,
         "item_id": item_id
     }
)

Notice the underscore in the type key. Your function is called update_price, so the type needs to be the same.

like image 155
Dalvtor Avatar answered Oct 21 '25 16:10

Dalvtor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!