Jia*_*nbo 5 django django-channels
我试图用 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"],
})
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试从浏览器更新价格时,消费者可以从中收到消息,但无法成功调用该update_price函数。(sending new price从未打印过):
receive price 701
receive item_id 2
performing group send
Run Code Online (Sandbox Code Playgroud)
我只是按照这个例子: https://github.com/andrewgodwin/channels-examples/tree/master/multichat
任何建议将不胜感激!
基本上,从这里开始改变:
await self.channel_layer.group_send(
"bidding",
{
"type": "update.price"
"price": price,
"item_id": item_id
}
)
Run Code Online (Sandbox Code Playgroud)
对此:
await self.channel_layer.group_send(
"bidding",
{
"type": "update_price"
"price": price,
"item_id": item_id
}
)
Run Code Online (Sandbox Code Playgroud)
请注意键中的下划线type。您的函数被调用update_price,因此类型需要相同。
| 归档时间: |
|
| 查看次数: |
5682 次 |
| 最近记录: |