Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有更好的方法在线程中运行uvicorn?_Python_Python Multithreading_Uvicorn - Fatal编程技术网

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

Python 有没有更好的方法在线程中运行uvicorn?,python,python-multithreading,uvicorn,Python,Python Multithreading,Uvicorn,Uvicorn不会在线程内运行,因为信号在线程中不起作用。 只需移除信号处理即可停止服务器关闭(需要强制关闭) 我的解决方案是使用\uuuuu new\uuuuu函数获取服务器对象并创建一个关机函数,然后将其绑定到线程外的信号 然而,这是一个非常丑陋的解决方案。有更好的方法吗 def run(): ''' Start uvicorn server returns exit function ''' server = None old_new =

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

我的解决方案是使用
\uuuuu new\uuuuu
函数获取服务器对象并创建一个关机函数,然后将其绑定到线程外的信号

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

def run():
    '''
    Start uvicorn server
    returns exit function
    '''
    server = None

    old_new = uvicorn.Server.__new__

    def spoof_server(self, *_, **__):
        '''Interfeer with __new__ to set server'''
        nonlocal server
        server = old_new(self)
        return server

    uvicorn.Server.__new__ = spoof_server
    uvicorn.Server.install_signal_handlers = lambda *_, **__: None

    Thread(target=uvicorn.run, args=[make_app()]).start()

    def exit_server():
        print('exiting...')
        server.handle_exit(None, None)

    return exit_server

我也在找类似的东西。我发现这个答案对我很有帮助。

我将在此处发布该片段:

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.

我不知道Uvicorn的答案,但是Hypercorn(另一个ASGI服务器)可以做到这一点——请看这些。(觉得这总比什么都没有好)谢谢你的建议!我最后做的是转到aiohttp,它也可以这样做。