2016-06-20 3 views
2

aioweb 프레임 워크 내에서 coroutine 처리기에서 비동기 프로세스를 실행하는 방법을 이해하려고합니다. 여기에 코드의 예입니다aiohttp에서 처리기에서 비동기 프로세스를 실행하는 방법

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 기능을 실행합니다. 누군가가 그것을 어떻게 달성 할 수 있는지 예를 들어 줄 수 있습니까? 내가 처리기 내에서 메인 이벤트 루프를 전달/사용하고 그 자체로 비동기 프로세스를 실행할 수있는 다른 함수로 전달하는 방법을 이해하는 데 어려움이있다.

답변

3

나는 당신이 당신의 주요 handle 기능에 asyncio.ensure_future를 사용 (코 루틴 같은 기능을 포장 할 수있는 일을해야 async def) 코 루틴으로 기존의 process 함수를 정의해야한다 같아요. 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") 

결과 대기/실행을 중단하지 않고 동시 루틴의 실행 (케이스의 process 기능)을 예약한다 ensure_future 방법.

내 생각에 당신이 찾고있는 내용은 다음과 같은 기존 게시물과 관련 될 수 있습니다. "Fire and forget" python async/await

관련 문제