python aiohttp 进入现有的事件循环

标签 python python-asyncio aiohttp

我正在测试 aiohttp 和 asyncio。我希望相同的事件循环具有套接字、http 服务器、http 客户端。

我正在使用此示例代码:

@routes.get('/')
async def hello(request):
    return web.Response(text="Hello, world")

app = web.Application()
app.add_routes(routes)
web.run_app(app)

问题是run_app正在阻塞。我想将 http 服务器添加到我使用以下方法创建的现有事件循环中:
asyncio.get_event_loop()

最佳答案

The problem is run_app is blocking. I want to add the http server into an existing event loop

run_app只是一个方便的API。要挂接到现有的事件循环,您可以直接实例化 AppRunner :
loop = asyncio.get_event_loop()
# add stuff to the loop
...

# set up aiohttp - like run_app, but non-blocking
runner = aiohttp.web.AppRunner(app)
loop.run_until_complete(runner.setup())
site = aiohttp.web.TCPSite(runner)    
loop.run_until_complete(site.start())

# add more stuff to the loop
...

loop.run_forever()
在 asyncio 3.8 及更高版本中,您可以使用 asyncio.run() :
async def main():
    # add stuff to the loop, e.g. using asyncio.create_task()
    ...

    runner = aiohttp.web.AppRunner(app)
    await runner.setup()
    site = aiohttp.web.TCPSite(runner)    
    await site.start()

    # add more stuff to the loop, if needed
    ...

    # wait forever
    await asyncio.Event().wait()

asyncio.run(main())

关于python aiohttp 进入现有的事件循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53465862/

相关文章:

python - 异步: Why is awaiting a cancelled Future not showing CancelledError?

python - 使用 python 和 networkx 进行大图可视化

python - 异步: terminating all tasks when one of them throws exception

python - python 3 asyncio 中是否有类似 socket.recv_into 的操作?

python - 在 Python 类中使用 asyncio 和 aiohttp

python - 在 aiohttp 或 httpx 中,我需要在应用程序关闭时关闭 session /客户端吗

python - TypeError : An asyncio. Future,需要协程或等待

python - SQLAlchemy 属性错误 : 'Query' object has no attribute '_sa_instance_state' when retrieving from database

python - 学习 Python 和使用字典

Python 2.5和2.6与Numpy兼容性问题