我正在使用 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 发送请求的代码我应该首先为每个设备创建会话和登录,当我添加尝试时,除了捕获 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()