在使用aiohttp持久会话时,可能会遇到RuntimeError。为了解决这个问题,可以尝试以下方法:
raise_for_status
为False:在使用ClientSession
创建会话时,将raise_for_status
参数设置为False。这样可以防止在发生非2xx状态码时抛出异常。你可以在代码中使用try-except块来处理异常。import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
response.raise_for_status()
return await response.text()
async def main():
async with aiohttp.ClientSession(raise_for_status=False) as session:
try:
html = await fetch(session, 'https://example.com')
print(html)
except aiohttp.ClientResponseError as e:
print(f'Error: {e}')
if __name__ == '__main__':
asyncio.run(main())
await response.read()
替代await response.text()
:有时,在使用response.text()
时可能会引发RuntimeError。可以尝试使用response.read()
替代,这是一个更底层的方法来读取响应内容。import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
response.raise_for_status()
return await response.read()
async def main():
async with aiohttp.ClientSession() as session:
try:
data = await fetch(session, 'https://example.com')
html = data.decode('utf-8')
print(html)
except aiohttp.ClientResponseError as e:
print(f'Error: {e}')
if __name__ == '__main__':
asyncio.run(main())
以上是两种可能的解决方法。根据具体情况,你可以选择其中一种或尝试两种方法来解决aiohttp持久会话的RuntimeError问题。