Last active
January 10, 2022 21:25
-
-
Save kissgyorgy/ee07f59ed19886e7f473a99222f9a683 to your computer and use it in GitHub Desktop.
Python: Handle cancellation in an asyncio background task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import httpx | |
async def infinite_loop(backend_client): | |
while True: | |
try: | |
await asyncio.sleep(3) | |
except asyncio.CancelledError: | |
print("Cancelled") | |
await backend_client.aclose() | |
break | |
try: | |
asyncio.run(infinite_loop(httpx.AsyncClient())) | |
except KeyboardInterrupt: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment