How to run an aiohttp server in a thread?

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

    There's a new API intended for this use case:

    https://docs.aiohttp.org/en/stable/web_advanced.html#application-runners

    from aiohttp import web
    import asyncio
    
    
    async def healthz(request):
        return web.Response(text="OK")
    
    app = web.Application()
    app.add_routes([web.get("/", healthz)])
    
    
    async def runner():
        runner = web.AppRunner(app)
        await runner.setup()
        site = web.TCPSite(runner, "localhost", 8080)
        await site.start()
    
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(runner())
    
    

提交回复
热议问题