Skip to content
Myr

compat.py

This file

Path

httpcore/compat.py

51 lines · 1.6 KiB · Python

Last changed by

Add SyncConnectionPoolTom Christiebefore adoption4a36ec7

History of this file

Take it

1import asyncio23if hasattr(asyncio, "run"):4    asyncio_run = asyncio.run5else:  # pragma: nocover67    def asyncio_run(main, *, debug=False):  # type: ignore8        if asyncio._get_running_loop() is not None:9            raise RuntimeError(10                "asyncio.run() cannot be called from a running event loop"11            )1213        if not asyncio.iscoroutine(main):14            raise ValueError("a coroutine was expected, got {!r}".format(main))1516        loop = asyncio.new_event_loop()17        try:18            asyncio.set_event_loop(loop)19            loop.set_debug(debug)20            return loop.run_until_complete(main)21        finally:22            try:23                _cancel_all_tasks(loop)24                loop.run_until_complete(loop.shutdown_asyncgens())25            finally:26                asyncio.set_event_loop(None)27                loop.close()2829    def _cancel_all_tasks(loop):  # type: ignore30        to_cancel = asyncio.all_tasks(loop)31        if not to_cancel:32            return3334        for task in to_cancel:35            task.cancel()3637        loop.run_until_complete(38            tasks.gather(*to_cancel, loop=loop, return_exceptions=True)39        )4041        for task in to_cancel:42            if task.cancelled():43                continue44            if task.exception() is not None:45                loop.call_exception_handler(46                    {47                        "message": "unhandled exception during asyncio.run() shutdown",48                        "exception": task.exception(),49                        "task": task,50                    }51                )