How to run an aiohttp server in a thread?

前端 未结 4 1054
独厮守ぢ
独厮守ぢ 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:23

    It's possible to use web.run_app, just create a new event loop (and set handle_signals=False to avoid RuntimeError: set_wakeup_fd only works in main thread):

    import threading
    import asyncio
    from aiohttp import web
    
    def aiohttp_server():
        def say_hello(request):
            return web.Response(text='Hello, world')
    
        asyncio.set_event_loop(asyncio.new_event_loop())  # create a new event loop here
        app = web.Application(debug=True)
        app.add_routes([web.get('/', say_hello)])
        web.run_app(app, handle_signals=False)
    

提交回复
热议问题