文中使用httpx进行异步请求,如果使用aiohttp(通过pip install aiohttp命令安装)进行异步请求时,使用loop.close()关闭事件循环时会抛出异常raise RuntimeError('Event loop is closed')【Python 版本 3.9】。相关代码如下:
import aiohttp import asyncio
asyncdeffetch_asyncio(session, url): asyncwith session.get(url) as response: returnawait response.json()
asyncdeftest_asyncio(): urls = ['https://httpbin.org/get', 'https://httpbin.org/cookies', 'https://httpbin.org/uuid', 'https://httpbin.org/response-headers?freeform='] asyncwith aiohttp.ClientSession() as session: tasks = [asyncio.ensure_future(fetch_asyncio(session, url)) for url in urls] responses = await asyncio.wait(tasks) return responses
defmain(): # 其他流程 loop = asyncio.get_event_loop() responses = loop.run_until_complete(test_asyncio()) for response in responses: print(response) loop.close() # 其他流程
if __name__ == '__main__': main()
5.1 运行报错结果
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000118E6D784C0> Traceback (most recent call last): File "C:\Program Files\Python39\lib\asyncio\proactor_events.py", line 116, in __del__ self.close() File "C:\Program Files\Python39\lib\asyncio\proactor_events.py", line 108, in close self._loop.call_soon(self._call_connection_lost, None) File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 746, in call_soon self._check_closed() File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 510, in _check_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed