问题描述
我正在使用 Python 包 aiohttp
并想访问 async with
块中的 response
表达式(with-item except
):
try:
async with session.get(url,params={'user_id': user_id}) as response:
return await response.json()
except (ClientConnectionError,asyncio.TimeoutError) as e:
logger.error(f'{response.url} raised {e}')
raise
据我所知,response
的上下文在 ClientConnectionError
或 asyncio.TimeoutError
被引发时关闭,因为它位于 async width
块之外。因此,调用 response.url
会引发 UnboundLocalError
。
如何手动使用 __aenter__
和 __aexit__
(请参阅 PEP 492)重写上述代码段并将响应上下文保留在 except
块中?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)