2020-12-24 05:55:19 +00:00
|
|
|
import contextlib
|
|
|
|
import threading
|
2020-12-25 19:07:12 +00:00
|
|
|
import time
|
|
|
|
|
2020-12-24 05:55:19 +00:00
|
|
|
import uvicorn
|
|
|
|
|
|
|
|
|
2021-09-03 20:05:40 +00:00
|
|
|
def asyncio_setup() -> None: # pragma: no cover
|
|
|
|
# Set eventloop for win32 setups
|
|
|
|
# Reverts a change done in uvicorn 0.15.0 - which now sets the eventloop
|
|
|
|
# via policy.
|
|
|
|
import sys
|
|
|
|
|
|
|
|
if sys.version_info >= (3, 8) and sys.platform == "win32":
|
|
|
|
import asyncio
|
|
|
|
import selectors
|
|
|
|
selector = selectors.SelectSelector()
|
|
|
|
loop = asyncio.SelectorEventLoop(selector)
|
|
|
|
asyncio.set_event_loop(loop)
|
|
|
|
|
|
|
|
|
2020-12-24 05:55:19 +00:00
|
|
|
class UvicornServer(uvicorn.Server):
|
|
|
|
"""
|
|
|
|
Multithreaded server - as found in https://github.com/encode/uvicorn/issues/742
|
2021-03-13 00:16:03 +00:00
|
|
|
|
|
|
|
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
|
2020-12-24 05:55:19 +00:00
|
|
|
"""
|
2021-03-13 00:16:03 +00:00
|
|
|
|
|
|
|
def run(self, sockets=None):
|
|
|
|
import asyncio
|
|
|
|
|
2020-12-27 09:56:19 +00:00
|
|
|
"""
|
2021-03-13 00:16:03 +00:00
|
|
|
Parent implementation calls self.config.setup_event_loop(),
|
|
|
|
but we need to create uvloop event loop manually
|
2020-12-27 09:56:19 +00:00
|
|
|
"""
|
2021-03-13 00:16:03 +00:00
|
|
|
try:
|
|
|
|
import uvloop # noqa
|
|
|
|
except ImportError: # pragma: no cover
|
2021-09-03 20:05:40 +00:00
|
|
|
|
2021-03-13 00:16:03 +00:00
|
|
|
asyncio_setup()
|
|
|
|
else:
|
|
|
|
asyncio.set_event_loop(uvloop.new_event_loop())
|
2021-08-17 04:54:10 +00:00
|
|
|
try:
|
2021-12-31 12:01:13 +00:00
|
|
|
loop = asyncio.get_running_loop()
|
2021-08-17 04:54:10 +00:00
|
|
|
except RuntimeError:
|
|
|
|
# When running in a thread, we'll not have an eventloop yet.
|
|
|
|
loop = asyncio.new_event_loop()
|
2021-03-13 00:16:03 +00:00
|
|
|
loop.run_until_complete(self.serve(sockets=sockets))
|
2020-12-24 05:55:19 +00:00
|
|
|
|
|
|
|
@contextlib.contextmanager
|
|
|
|
def run_in_thread(self):
|
|
|
|
self.thread = threading.Thread(target=self.run)
|
|
|
|
self.thread.start()
|
|
|
|
while not self.started:
|
|
|
|
time.sleep(1e-3)
|
|
|
|
|
|
|
|
def cleanup(self):
|
|
|
|
self.should_exit = True
|
|
|
|
self.thread.join()
|