代码之家  ›  专栏  ›  技术社区  ›  atline

结合asyncio和aiohttp时,“RuntimeError:此事件循环已在运行”

  •  0
  • atline  · 技术社区  · 5 年前

    不像 such post 下一个场景是:

    • 我已经有一个asyncio程序运行良好,比如next:
    import asyncio
    
    async def action():
        print("action")
        # use sleep to simulate real operation
        # it's a daemon works endless there
        await asyncio.sleep(10000)
    
    async def main():
        await action()
    
    if __name__ == '__main__':
        asyncio.run(main())
    
    • 然后,我想为我的程序添加一个rest api。有了它,客户端可以通过api调用查询我的程序的某些状态(例如,获取我的asyncio程序逻辑的一些内部状态变量):
    import asyncio
    from aiohttp import web
    
    async def handle(request):
        name = request.match_info.get('name', "Anonymous")
        text = "Hello, " + name
        return web.Response(text=text)
    
    async def start_api_server():
        print("api")
        app = web.Application()
        app.add_routes([web.get('/', handle),
                        web.get('/{name}', handle)])
        web.run_app(app)
    
    async def action():
        print("action")
        await asyncio.sleep(10000)
    
    async def main():
        #await action()
        await(asyncio.gather(start_api_server(), action()))
    
    if __name__ == '__main__':
        asyncio.run(main())
    

    但是,上面的报告下一个堆栈:

    Traceback (most recent call last):
      File "svr.py", line 26, in <module>
        asyncio.run(main())
      File "/usr/lib/python3.7/asyncio/runners.py", line 43, in run
        return loop.run_until_complete(main)
      File "/usr/lib/python3.7/asyncio/base_events.py", line 579, in run_until_complete
        return future.result()
      File "svr.py", line 23, in main
        await(asyncio.gather(start_api_server(), action()))
      File "svr.py", line 15, in start_api_server
        web.run_app(app)
      File "/home/cake/venv/lib/python3.7/site-packages/aiohttp/web.py", line 512, in run_app
        _cancel_tasks({main_task}, loop)
      File "/home/cake/venv/lib/python3.7/site-packages/aiohttp/web.py", line 444, in _cancel_tasks
        asyncio.gather(*to_cancel, loop=loop, return_exceptions=True)
      File "/usr/lib/python3.7/asyncio/base_events.py", line 566, in run_until_complete
        self.run_forever()
      File "/usr/lib/python3.7/asyncio/base_events.py", line 521, in run_forever
        raise RuntimeError('This event loop is already running')
    RuntimeError: This event loop is already running
    

    问题:

    看起来我们无法在combinaton上实现,所以我想知道向asyncio程序添加rest api的正确方法是什么?

    注: 如果可能的话,我想避免运行另一个线程来启动web服务器,除非完全不可能。

    0 回复  |  直到 5 年前
        1
  •  0
  •   atline    5 年前

    我从中找到了答案 aiohttp source code :

    • 网状物运行应用程序(应用程序) 作为下一个:
    async def _run_app(......):
    
        runner = AppRunner(
            app,
            handle_signals=handle_signals,
            access_log_class=access_log_class,
            access_log_format=access_log_format,
            access_log=access_log,
        )
    
        await runner.setup()
        ......
        while True:
            await asyncio.sleep(delay)
    
    def run_app(......):
    
        loop = asyncio.get_event_loop()
        try:
            main_task = loop.create_task(
                _run_app(
                    app,
                    ......
                )
            )
            loop.run_until_complete(main_task)
    

    但它会直接呼叫 loop.run_until_complete 这使得我们不可能启动我们自己的事件循环 asyncio.run() 在主程序中。

    • 为了克服这个问题,我们应该使用一些低级函数作为下一步:
    import asyncio
    from aiohttp import web
    
    
    async def handle(request):
        name = request.match_info.get('name', "Anonymous")
        text = "Hello, " + name
        return web.Response(text=text)
    
    async def start_api_server():
        print("api")
        loop = asyncio.get_event_loop()
        app = web.Application()
        app.add_routes([web.get('/', handle),
                        web.get('/{name}', handle)])
        #web.run_app(app)
        runner = web.AppRunner(app)
        await runner.setup()
        await loop.create_server(runner.server, '127.0.0.1', 8080)
        print('Server started at http://127.0.0.1:8080...')
    
    async def action():
        print("action")
        await asyncio.sleep(10000)
    
    async def main():
        #await action()
        await(asyncio.gather(start_api_server(), action()))
    
    if __name__ == '__main__':
        asyncio.run(main())
    

    上面的代码重现了 runner setup 在里面 web.run_app ,然后把房子递给我 server 在里面 AppRunner 到 asyncio.create_server 新的aiohttp服务器。然后可以在中重用eventloop asyncio.run 来满足我的要求。