python aiohttp 进入现有的事件循环 [英] python aiohttp into existing event loop

查看:33
本文介绍了python aiohttp 进入现有的事件循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm testing aiohttp and asyncio. I want the same event loop to have a socket, http server, http client.

我正在使用此示例代码:

I'm using this sample code:

@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 服务器添加到我创建的现有事件循环中:

The problem is run_app is blocking. I want to add the http server into an existing event loop, that I create using:

asyncio.get_event_loop()

推荐答案

问题是 run_app 被阻塞了.我想将 http 服务器添加到现有的事件循环中

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

run_app 只是一个方便的 API.要挂钩现有的事件循环,您可以直接实例化 AppRunner:

run_app is just a convenience API. To hook into an existing event loop, you can directly instantiate the 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():

In asyncio 3.8 and later you can use 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 进入现有的事件循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆