如何 运行 从 aiohttp 中的处理程序异步处理

How to run async process from handler in aiohttp

我正在尝试了解如何从 aioweb 框架内的协程处理程序 运行 异步进程。这是一个代码示例:

def process(request):
    # this function can do some calc based on given request
    # e.g. fetch/process some data and store it in DB
    # but http handler don't need to wait for its completion

async def handle(request):
    # process request
    process(request) ### THIS SHOULD RUN ASYNCHRONOUSLY

    # create response
    response_data = {'status': 'ok'}

    # Build JSON response
    body = json.dumps(response_data).encode('utf-8')
    return web.Response(body=body, content_type="application/json")

def main():
    loop = asyncio.get_event_loop()
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handle)

    server = loop.create_server(app.make_handler(), '127.0.0.1', 8000)
    print("Server started at http://127.0.0.1:8000")
    loop.run_until_complete(server)
    try:
       loop.run_forever()
    except KeyboardInterrupt:
       pass

if __name__ == '__main__':
   main()

我想 运行 process 从处理程序异步运行。有人可以举例说明我如何实现这一目标。我很难理解如何在处理程序中 pass/use 主事件循环并将其传递给另一个函数,该函数本身可以 运行 在其中进行异步处理。

我猜你应该将现有的 process 函数定义为协程(async def 应该完成将你的函数包装为协程的工作)并在你的主 handle函数。

async def process(request):
    # Do your stuff without having anything to return

async def handle(request):
    asyncio.ensure_future(process(request))
    body = json.dumps({'status': 'ok'}).encode('utf-8')
    return web.Response(body=body, content_type="application/json")

根据 asyncio documention ensure_future 方法应该安排协程的执行(在你的情况下是 process 函数)没有 blocking/waiting一个结果。

我想您要查找的内容可能与一些现有帖子有关,例如: