我需要一些帮助来理解Django通道是如何执行代码的。我可能对sync和async缺少一些理解,因为它没有达到我所期望的效果。你知道吗
总而言之,我希望消费者能够做到以下几点:
group_send
广播结果这是行不通的,所以我试图创建一个非常简单的消费者来了解发生了什么。你知道吗
我创建了一个WebsocketConsumer
,就像我想让它运行syncronously
,也就是说,我希望每个循环执行,然后广播结果,然后再次执行。你知道吗
当我触发receive方法时,我看到self.send
会立即发生,但这两个方法都是“2。第一组呼叫“和”3。第二个组调用“发生在长时间运行的函数之后。我可以从console.log
中的时间戳看出,chat_message()
只针对“2执行。在长时间运行的函数之后的第一个组调用“,即使它出现在receive
方法中长时间运行的函数之前。你知道吗
其中一个浏览器控制台中的结果是:
粗体的时间戳是receive方法启动时的时间戳。 “chat start”时间戳是调用chat\u message方法的时间。你知道吗
class MyConsumer(WebsocketConsumer):
groups = ["my_group"]
def connect(self):
print("connected")
self.accept()
def receive(self, text_data=None, bytes_data=None):
ts = datetime.now().strftime("%H:%M:%S.%f")
self.send(text_data=json.dumps("1. Self send {}".format(ts)))
text_data = "2. {} first group call".format(ts)
async_to_sync(self.channel_layer.group_send)(
"my_group",
{
"type": "chat.message",
"text": text_data,
},
)
text_data = self.long_running_function(ts)
async_to_sync(self.channel_layer.group_send)(
"my_group",
{
"type": "chat.message",
"text": text_data,
},
)
def disconnect(self, close_code):
print("disconnected")
async_to_sync(self.channel_layer.group_discard)("my_group", self.channel_name)
def chat_message(self, event):
chat_msg_start_time = datetime.now().strftime("%H:%M:%S.%f")
text_data = "{} chat start: {}".format(event["text"], chat_msg_start_time)
self.send(text_data=json.dumps(text_data))
def long_running_function(self, ts):
start_time = datetime.now().strftime("%H:%M:%S.%f")
time.sleep(2)
end_time = datetime.now().strftime("%H:%M:%S.%f")
msg = "3. {} second group send lrf start_time: {} lrf end_time: {}".format(ts, start_time, end_time)
return msg
目前没有回答
相关问题 更多 >
编程相关推荐