Upgrade to Pro — share decks privately, control downloads, hide ads and more …

asyncio: it's all about the cancellation by Bru...

Pycon ZA
October 06, 2017

asyncio: it's all about the cancellation by Bruce Merry

Lightning Talk at PyConZA 2017

Pycon ZA

October 06, 2017
Tweet

More Decks by Pycon ZA

Other Decks in Programming

Transcript

  1. ASYNCIO: IT’S ALL ABOUT THE CANCELLATION PyConZA 2017 Bruce Merry

    Bruce Merry asyncio: it’s all about the cancellation PyConZA 2017 1 / 5
  2. 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
  3. 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
  4. 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
  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
  6. 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
  7. 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
  8. 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