我从中找到了答案
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
来满足我的要求。