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

时间:2016-06-20 06:45:42

标签: python asynchronous aiohttp

我正在尝试了解如何在aioweb框架内从coroutine处理程序运行异步进程。以下是代码示例:

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函数。有人可以举例说明我是如何实现这一目标的。我很难理解如何在处理程序中传递/使用主事件循环并将其传递给另一个函数,该函数本身可以在其中运行异步进程。

1 个答案:

答案 0 :(得分:6)

我想你应该将现有的process函数定义为协程(async def应该完成将函数包装为协程的工作)并在主{{1}中使用asyncio.ensure_future功能。

handle

根据asyncio documention 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") 方法应安排执行协程(在您的情况下为ensure_future函数)而不阻塞/等待结果

我猜您要查找的内容可能与某些现有帖子有关:"Fire and forget" python async/await