from channels.generic.websocket import WebsocketConsumer from iot.models import EspMsgTest from asgiref.sync import async_to_sync class iotConsumer(WebsocketConsumer): def connect(self): self.accept() # 接受 WebSocket 连接 def disconnect(self, close_code): pass def receive(self, text_data): if text_data == "wokao": object = EspMsgTest(content="WOKAO") object.save() else : object = EspMsgTest(content="NOBODY") object.save() def send_message(self, message): self.send(text_data=message)