我正在尝试使用django-channels实现竞标模块。基本上,我会广播从客户端收到的任何消息,我的消费者部分如下代码片段所示:
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"],
})
但是当我尝试从浏览器更新价格时,消费者可以收到消息,但它无法成功调用update_price
函数。(sending new price
从未被打印):
receive price 701
receive item_id 2
performing group send
我只是在按照这个例子进行操作: https://github.com/andrewgodwin/channels-examples/tree/master/multichat
如果有任何建议,将不胜感激!