我正在尝试使用Django渠道实施出价模块。基本上,我广播从客户端收到的任何消息,而消费者部分则使用以下代码段:
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
任何建议将不胜感激!
答案 0 :(得分:0)
基本上,从此更改:
await self.channel_layer.group_send(
"bidding",
{
"type": "update.price"
"price": price,
"item_id": item_id
}
)
对此:
await self.channel_layer.group_send(
"bidding",
{
"type": "update_price"
"price": price,
"item_id": item_id
}
)
请注意type
键中的下划线。您的函数称为update_price
,因此类型必须相同。
答案 1 :(得分:0)
这可能对您有所帮助:
在routing.py 中尝试使用path("", MainConsumer.as_asgi())
而不是path("", MainConsumer)
。