这是我的 django 通道代码。如何获取它给出错误的数据您不能从异步上下文调用它 - 使用线程或 sync_to_async。
WaitlistConsumer 类(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
try:
asyncio.ensure_future(self.send_data())
except Exception as e:
print(e)
async def disconnect(self, close_code):
self.task.cancel()
async def send_data(self):
while True:
await asyncio.sleep(3)
try:
waitlist =await sync_to_async(Waitlist.objects.all)()
print(waitlist)
if waitlist.exists():
print("first name")
data={"first_name":waitlist[0].first_name}
else:
data = {"first_name": "No one is waiting"}
await self.send(json.dumps(data))
except Exception as e:
print(e)