如何运行从Python程序很多aiohttp服务器

如何运行从Python程序很多aiohttp服务器

问题描述:

如何从1个Python程序运行许多aiohttp服务器 例子:如何运行从Python程序很多aiohttp服务器

manager = Manager() 
server1 = manager.create_server(config1) 
server2 = manager.create_server(config2) 
server1.run() # here program stop 
server2.run() # but i want to run these two servers at the same time 

我想使用threading.Thread(),使许多线程和运行的服务器有 但得到这个错误:

RuntimeError: There is no current event loop in thread 'thname' 

我尝试用户loop.run_in_executor(),但这种方式没有任何反应, 程序完成没有错误,服务器无法运行。

这是服务器运行功能

def run(self, port, host): 
     app = web.Application() 
     app.router.add_post('/', self._get_update) 
     web.run_app(app, host=host, port=port) 
+0

https://*.com/questions/44850701/multiple-aiohttp-applications-running-in-the-same-process – Juggernaut

我找到答案

首先

def run(self, host, port): 
    app = web.Application() # make app 
    app.router.add_post('/', self._get_update) # add handlers 
    handler = app.make_handler() # make handlers 
    server = loop.create_server(handler, host, port) #create server 
    loop.run_until_complete(server) # this is the most important string, as i'v understood it run server on the loop and then return loop to a waiting state. 
    print("======== Running on {} ========\n".format(host+":"+str(port))) # info message 

然后我们可以做旁边

server1.run(host, port1) 
server2.run(host, port2) 
loop.run_forever() 

而且一切都会好的!