async def index(self,request):
content = open(os.path.join(self.ROOT, "index.html"), encoding="utf8").read()
while(True):
time.sleep(1)
#if request["status"] == "disconnected":
# break
...
...
如何知道 aiohttp 请求中客户端何时断开连接?
在aiohttp中,可以通过监听request.transport对象来检查客户端是否断线。 request.transport 对象表示与当前请求关联的传输层(TCP、SSL 等)。
from aiohttp import web
class YourView(web.View):
async def index(self, request):
content = open(os.path.join(self.ROOT, "index.html"), encoding="utf8").read()
while True:
await asyncio.sleep(1)
# Check if the transport is closed/disconnected
if request.transport is None or request.transport.is_closing():
break
# Your other logic here...
# Any cleanup or finalization logic after the loop
...
return web.Response(text="Done")