Python package - aiohttp has a warning message "Unclosed client session"
My code is as follows:
import asyncio
import aiohttp
urls = [
'http://www.163.com/',
'http://www.sina.com.cn/',
]
async def get_url_data(u):
resp = await aiohttp.ClientSession().get(url=u)
headers = resp.headers
return headers
async def request_url(u):
res = await get_url_data(u)
return res
loop = asyncio.get_event_loop()
task_lists = asyncio.wait([request_url(u) for u in urls])
loop.run_until_complete(task_lists)
loop.close()
When I running my code, it's display a warning message:
Unclosed client session
Anybody can give me some solutions about that?You should close the connection in the end. You have 2 options: You can close the connection manually: import aiohttp session = aiohttp.ClientSession() # use the session here await session.close() Or you can use it with a context manager: import aiohttp import asyncio async def fetch(client): async with client.get('http://python.org') as resp: assert resp.status == 200 return await resp.text() async def main(loop): async with aiohttp.ClientSession(loop=loop) as client: html = await fetch(client) print(html) loop = asyncio.get_event_loop() loop.run_until_complete(main(loop)) The client session supports the context manager protocol for self closing.
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/041ac9882d5f7acd319bf46a5d5f8ace41ecfa8d5c1c0533efac96e43cd3e89d