Share
Embed
asyncio: it's all about the cancellation by Bruce Merry
Lightning Talk at PyConZA 2017
Pycon ZA
October 06, 2017
Transcript
8 slides
-
ASYNCIO: IT’S ALL ABOUT THE CANCELLATION PyConZA 2017 Bruce Merry
Bruce Merry asyncio: it’s all about the cancellation PyConZA 2017 1 / 5 -
Simple Server Example async def do_connection(reader, writer): try: while True:
line = await reader.readline() if not line: break # Connection was closed writer.write(await process(line)) finally: writer.close() Bruce Merry asyncio: it’s all about the cancellation PyConZA 2017 2 / 5 -
Simple Server Example async def do_connection(reader, writer): try: while True:
line = await reader.readline() if not line: break # Connection was closed writer.write(await process(line)) finally: writer.close() loop = asyncio.get_event_loop() task = loop.create_task(do_connection(reader, writer)) ... await task Bruce Merry asyncio: it’s all about the cancellation PyConZA 2017 2 / 5 -
Server Shutdown async def do_connection(reader, writer): try: while True: line
= await reader.readline() if not line: break # Connection was closed writer.write(await process(line)) finally: writer.close() Bruce Merry asyncio: it’s all about the cancellation PyConZA 2017 3 / 5 -
Server Shutdown async def do_connection(reader, writer): try: while True: line
= await reader.readline() if not line: break # Connection was closed writer.write(await process(line)) finally: writer.close() task.cancel() Bruce Merry asyncio: it’s all about the cancellation PyConZA 2017 3 / 5 -
Server Shutdown async def do_connection(reader, writer): try: while True: line
= await reader.readline() if not line: break # Connection was closed writer.write(await process(line)) finally: writer.close() task.cancel() CancelledError Bruce Merry asyncio: it’s all about the cancellation PyConZA 2017 3 / 5 -
Catching Cancellation async def do_connection(reader, writer): try: while True: line
= await reader.readline() if not line: break # Connection was closed writer.write(await process(line)) except asyncio.CancelledError: writer.write(b Server shutting down\n ) raise finally: writer.close() Bruce Merry asyncio: it’s all about the cancellation PyConZA 2017 4 / 5 -
Wait With Timeout try await asyncio.wait_for(task, timeout) except TimeoutError: ...
Bruce Merry asyncio: it’s all about the cancellation PyConZA 2017 5 / 5