aiohttp服务器断开连接错误

2024-10-01 04:53:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用aiohttp与设备API通信,我一次只发送一个设备的请求,并在发送另一个设备之前等待响应,当使用脚本一次查询多个设备时,我收到很多ServerDisconnectedError,但当仅在一个设备上运行时,它工作正常,没有任何错误

用于查询多个设备的配置的脚本

async def download_conf(devices, *args, **kwargs):
   semaphore = asyncio.Semaphore(5) # --> even with Semaphore I still get the error a lot
   async def create_semaphore_task():
       async with semaphore:
         downloader = await query_conf(device=device, *args, **kwargs)
       return downloader
   tasks = dict()
   for device in devices:
      tasks[device['name']] = asyncio.create_task(create_semaphore_task())
   results, pending = await asyncio.wait(tasks.values())

下面是向设备API发送请求的代码。首先,我应该为每个设备创建会话并首先登录,当我添加try except以捕获ServerDisconnectedError并再次尝试后,查询工作正常

async def request(self, method='GET', url='', **kwargs):
    retries = 2
    while retries > 0:
        try:
            self.resp = await self.session.request(method=method, url=url, **kwargs)
            break
        except (aiohttp.ServerDisconnectedError) as e:
            retries -= 1
            if retries == 0: raise e
            await asyncio.sleep(1)

    return await self.resp.read()

Tags: selfasynciourltaskasyncdevicedefcreate