How to run an aiohttp server in a thread?

前端 未结 4 1026
独厮守ぢ
独厮守ぢ 2021-01-18 02:18

This example of aiohttp server in a thread fails with an RuntimeError: There is no current event loop in thread \'Thread-1\'. error:

import thre         


        
4条回答
  •  梦谈多话
    2021-01-18 02:34

    We must use app.make_handler handler in main thread, example:

    import asyncio
    import threading
    from aiohttp import web
    
    loop = asyncio.get_event_loop()
    
    
    def say_hello(request):
        return web.Response(text='Hello, world')
    
    
    app = web.Application(debug=True)
    app.add_routes([web.get('/', say_hello)])
    
    handler = app.make_handler()
    server = loop.create_server(handler, host='127.0.0.1', port=8080)
    
    
    def aiohttp_server():
        loop.run_until_complete(server)
        loop.run_forever()
    
    
    t = threading.Thread(target=aiohttp_server)
    t.start()
    

提交回复
热议问题