简体   繁体   English

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

[英]How to run async process from handler in aiohttp

I'm trying to understand how to run an asynchronous process from coroutine handler within aioweb framework. 我试图了解如何在aioweb框架内从coroutine处理程序运行异步进程。 Here is an example of code: 这是一个代码示例:

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()

I want to run process function asynchronously from the handler. 我想从处理程序异步运行process函数。 Can someone provide an example how I can achieve that. 有人可以举例说明我是如何实现这一目标的。 I'm struggle to understand how I can pass/use main event loop within a handler and pass it around to another function which by itself can run async process within it. 我很难理解如何在处理程序中传递/使用主事件循环并将其传递给另一个函数,该函数本身可以在其中运行异步进程。

I guess you should define your existing process function as a coroutine ( async def should do the job to wrap your function as a coroutine) and use asyncio.ensure_future in your main handle function. 我想你应该将现有的process函数定义为协程( async def应该完成将函数包装为协程的工作)并在主handle函数中使用asyncio.ensure_future

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")

According to asyncio documention the ensure_future method should schedule the execution of the coroutine (the process function in your case) without blocking/waiting for a result. 根据asyncio文档ensure_future方法应该安排协程的执行(在您的情况下为process函数),而不会阻塞/等待结果。

I guess what you are looking for could be related to some existing posts like this one : "Fire and forget" python async/await 我想你要找的东西可能与一些现有的帖子有关,比如这个: “火与忘记”python async / await

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM