有没有更好的方法在线程中运行uvicorn?

时间:2019-09-19 11:35:41

标签: python python-multithreading uvicorn

Uvicorn将不在线程内运行,因为信号在线程中不起作用。 只需删除信号处理即可停止服务器关闭(需要强行关闭)

我的解决方案是干扰FormData函数以获取服务器对象并创建关闭函数,然后将其绑定到线程 之外的信号。

但是,这是一个非常丑陋的解决方案。有更好的方法吗?

__new__

1 个答案:

答案 0 :(得分:0)

我也在寻找这样的东西。我发现这个答案对我有帮助。 https://stackoverflow.com/a/64521239/13029591

我会在这里发布代码片段:

import contextlib
import time
import threading
import uvicorn

class Server(uvicorn.Server):
    def install_signal_handlers(self):
        pass

    @contextlib.contextmanager
    def run_in_thread(self):
        thread = threading.Thread(target=self.run)
        thread.start()
        try:
            while not self.started:
                time.sleep(1e-3)
            yield
        finally:
            self.should_exit = True
            thread.join()

config = Config("example:app", host="127.0.0.1", port=5000, log_level="info")
server = Server(config=config)

with server.run_in_thread():
    # Server is started.
    ...
    # Server will be stopped once code put here is completed
    ...

# Server stopped.
相关问题