From 22f692e53ad1ca949ba899b678f8c231bbd85d0e Mon Sep 17 00:00:00 2001 From: Jackson Law <178053+jlaw@users.noreply.github.com> Date: Fri, 12 Mar 2021 16:16:03 -0800 Subject: [PATCH] Create event loop manually if uvloop is available asyncio.get_event_loop() does not call new_event_loop() if current_thread() != main_thread() --- freqtrade/rpc/api_server/uvicorn_threaded.py | 27 +++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/freqtrade/rpc/api_server/uvicorn_threaded.py b/freqtrade/rpc/api_server/uvicorn_threaded.py index 1554a8e52..2f72cb74c 100644 --- a/freqtrade/rpc/api_server/uvicorn_threaded.py +++ b/freqtrade/rpc/api_server/uvicorn_threaded.py @@ -8,12 +8,33 @@ import uvicorn class UvicornServer(uvicorn.Server): """ Multithreaded server - as found in https://github.com/encode/uvicorn/issues/742 + + Removed install_signal_handlers() override based on changes from this commit: + https://github.com/encode/uvicorn/commit/ce2ef45a9109df8eae038c0ec323eb63d644cbc6 + + Cannot rely on asyncio.get_event_loop() to create new event loop because of this check: + https://github.com/python/cpython/blob/4d7f11e05731f67fd2c07ec2972c6cb9861d52be/Lib/asyncio/events.py#L638 + + Fix by overriding run() and forcing creation of new event loop if uvloop is available """ - def install_signal_handlers(self): + + def run(self, sockets=None): + import asyncio + """ - In the parent implementation, this starts the thread, therefore we must patch it away here. + Parent implementation calls self.config.setup_event_loop(), + but we need to create uvloop event loop manually """ - pass + try: + import uvloop # noqa + except ImportError: # pragma: no cover + from uvicorn.loops.asyncio import asyncio_setup + asyncio_setup() + else: + asyncio.set_event_loop(uvloop.new_event_loop()) + + loop = asyncio.get_event_loop() + loop.run_until_complete(self.serve(sockets=sockets)) @contextlib.contextmanager def run_in_thread(self):