How run many aiohttp servers from python program

603 views Asked by At

How can i run many aiohttp servers from 1 python program Example:

 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

I am trying to use threading.Thread() to make many threads and run servers there but get this error:

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

I try to user loop.run_in_executor(), but in this way nothing happens, program finishes without errors and servers not run.

This is server run function

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

There are 1 answers

0
Denis Kartavenko On

I found answer

First

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

So then we can do next

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

And all will be OK!