[python,aiohttp] Don't create persistent aiohttp.ClientSession in __init__ (#20292)

aiohttp's `ClientSession` & `TCPConnector` used to obtain an event loop in
__init__ (via `asyncio.get_event_loop`). However, as of https://github.com/aio-libs/aiohttp/pull/8512 both
classes now obtain the running event loop and won't potentially create one. This
makes it impossible to create `ClientSession` and `TCPConnector` objects outside
of coroutines, as `get_running_loop` must be called from a coroutine.

Thus we defer the creation of a `ClientSession` into the actual request and
cache it for later usage. Thereby we pay only a very small price on the first
request, but subsequent requests will not be any more expensive.
This commit is contained in:
Dan Čermák
2024-12-15 10:11:35 +01:00
committed by GitHub
parent d87a70dd93
commit cdfab4eee3
3 changed files with 62 additions and 76 deletions

View File

@@ -10,14 +10,6 @@ import petstore_api
HOST = 'http://localhost/v2'
class TestApiClient(unittest.IsolatedAsyncioTestCase):
async def test_context_manager_closes_client(self):
async with petstore_api.ApiClient() as client:
# pool_manager
self.assertFalse(client.rest_client.pool_manager.closed)
rest_pool_ref = client.rest_client.pool_manager
self.assertTrue(rest_pool_ref.closed)
async def test_ignore_operation_servers(self):
config = petstore_api.Configuration(host=HOST)
async with petstore_api.ApiClient(config) as client: