From 34c0eb7a1adc3891043af851d154d8a42e35e418 Mon Sep 17 00:00:00 2001 From: Frederik Aalund Date: Sat, 1 Jul 2017 00:30:34 +0200 Subject: [PATCH 1/2] Docs: Added graceful shutdown procedure to client --- docs/client.rst | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/docs/client.rst b/docs/client.rst index 76074bfd0b9..39f6e94ce06 100644 --- a/docs/client.rst +++ b/docs/client.rst @@ -739,3 +739,35 @@ reading procedures:: Timeout is cumulative time, it includes all operations like sending request, redirects, response parsing, consuming response, etc. + + +Graceful Shutdown +----------------- + +When ``ClientSession`` closes at the end of an ``async with`` block (or through a direct ``.close()`` call), the underlying connection remains open due to asyncio internal details. In practice, the underlying connection will close after a short while. However, if the event loop is stopped before the underlying connection is closed, an ``ResourceWarning: unclosed transport`` warning is emitted (when warnings are enabled). + +To avoid this situation, a small delay must be added before closing the event loop to allow any open underlying connections to close. + +For a ``ClientSession`` without SSL, a simple zero-sleep (``await asyncio.sleep(0)``) will suffice:: + + async def read_website(): + async with aiohttp.ClientSession() as session: + async with session.get('http://example.org/') as response: + await response.read() + + loop = asyncio.get_event_loop() + loop.run_until_complete(read_website()) + # Zero-sleep to allow underlying connections to close + loop.run_until_complete(asyncio.sleep(0)) + loop.close() + +For a ``ClientSession`` with SSL, the application must wait a short duration before closing:: + + ... + # Wait 250 ms for the underlying SSL connections to close + loop.run_until_complete(asyncio.sleep(0.250)) + loop.close() + +Note that the appropriate amount of time to wait will vary from application to application. + +All if this will eventually become obsolete when the asyncio internals are changed so that aiohttp itself can wait on the underlying connection to close. Please follow issue `#1925 `_ for the progress on this. From 626e40c2c4ce7e365c8e97a9919e9a31021d9420 Mon Sep 17 00:00:00 2001 From: Frederik Aalund Date: Sat, 1 Jul 2017 00:39:38 +0200 Subject: [PATCH 2/2] Changes: Create 2039.doc --- changes/2039.doc | 1 + 1 file changed, 1 insertion(+) create mode 100644 changes/2039.doc diff --git a/changes/2039.doc b/changes/2039.doc new file mode 100644 index 00000000000..e08b12deef7 --- /dev/null +++ b/changes/2039.doc @@ -0,0 +1 @@ +Add a graceful shutdown section to the client usage documentation.