Shorthand for running a coroutine in the default background thread pool executor and awaiting the result
(
corofn: Callable, timeout: float = GENERAL_TIMEOUT, *args, **kwargs
)
| 19 | |
| 20 | |
| 21 | def call_async_from_sync( |
| 22 | corofn: Callable, timeout: float = GENERAL_TIMEOUT, *args, **kwargs |
| 23 | ): |
| 24 | """Shorthand for running a coroutine in the default background thread pool executor |
| 25 | and awaiting the result |
| 26 | """ |
| 27 | if corofn is None: |
| 28 | raise ValueError('corofn is None') |
| 29 | if not asyncio.iscoroutinefunction(corofn): |
| 30 | raise ValueError('corofn is not a coroutine function') |
| 31 | |
| 32 | async def arun(): |
| 33 | coro = corofn(*args, **kwargs) |
| 34 | result = await coro |
| 35 | return result |
| 36 | |
| 37 | def run(): |
| 38 | loop_for_thread = asyncio.new_event_loop() |
| 39 | try: |
| 40 | asyncio.set_event_loop(loop_for_thread) |
| 41 | return asyncio.run(arun()) |
| 42 | finally: |
| 43 | loop_for_thread.close() |
| 44 | |
| 45 | if getattr(EXECUTOR, '_shutdown', False): |
| 46 | result = run() |
| 47 | return result |
| 48 | |
| 49 | future = EXECUTOR.submit(run) |
| 50 | futures.wait([future], timeout=timeout or None) |
| 51 | result = future.result() |
| 52 | return result |
| 53 | |
| 54 | |
| 55 | async def call_coro_in_bg_thread( |