可以使用timeout参数设置请求超时时间,例如:
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=10) as response:
html = await response.text()
在创建客户端会话时,可以将TCPKeepAlive参数设置为True,以保持连接活动状态。例如:
connector = aiohttp.TCPConnector(keepalive_timeout=120,
enable_tcp_keepalive=True,
keepalive_idles=3)
async with aiohttp.ClientSession(connector=connector) as session:
async with session.get(url) as response:
html = await response.text()
如果请求长时间无响应,则可以添加重试机制,以尝试重新连接。例如:
async def get_url(url, retry=3):
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=10) as response:
html = await response.text()
except aiohttp.ClientTimeout:
if retry > 0:
await asyncio.sleep(5)
return await get_url(url, retry=retry-1)
else:
raise
return html