[파이썬] aiohttp 비동기 작업 취소 처리하기

웹 개발에서는 종종 비동기 작업을 수행해야 합니다. 이를 효과적으로 처리하기 위해 Python에서는 aiohttp라는 라이브러리를 제공합니다. aiohttp는 비동기 웹 서버 및 클라이언트 개발을 위한 강력한 도구이며, 이를 통해 여러 웹 요청을 동시에 처리할 수 있습니다.

그러나 비동기 작업을 취소하는 경우도 있을 수 있습니다. 예를 들어, 사용자가 요청을 취소하거나 타임아웃이 발생한 경우 해당 작업을 즉시 종료해야 할 수 있습니다. 그렇다면 aiohttp에서 비동기 작업을 취소하는 방법을 알아보겠습니다.

취소 가능한 태스크 만들기

aiohttp에서 태스크를 취소하기 위해서는 asyncio.Task를 사용해야 합니다. asyncio.ensure_future() 함수를 사용하여 비동기 함수를 Task로 변환할 수 있습니다.

아래는 aiohttp를 사용하여 GET 요청을 보내는 예제입니다.

import asyncio
import aiohttp

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        url = 'https://www.example.com'
        task = asyncio.ensure_future(fetch(session, url))
        response = await task
        print(response)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

위의 코드에서 fetch() 함수는 aiohttp를 사용하여 GET 요청을 보내고 응답을 반환합니다. main() 함수에서는 fetch()를 통해 비동기 작업을 실행한 후 결과를 출력합니다.

비동기 작업 취소하기

이제 비동기 작업을 취소하는 방법을 살펴보겠습니다. aiohttp에서는 asyncio.Task 객체의 cancel() 메서드를 사용하여 비동기 작업을 취소할 수 있습니다.

아래는 main() 함수를 수정하여 비동기 작업을 취소하는 예제입니다.

import asyncio
import aiohttp

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        url = 'https://www.example.com'
        task = asyncio.ensure_future(fetch(session, url))
        
        # 비동기 작업 실행
        response = await task
        print(response)
        
        # 비동기 작업 취소
        task.cancel()

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

위의 코드에서는 task.cancel()을 사용하여 비동기 작업을 즉시 종료합니다. task.cancel()을 호출하면 fetch() 함수에서 실행 중인 작업이 중단되고, await task 코드에서 asyncio.CancelledError 예외가 발생합니다. 따라서 이 예외를 처리하여 작업이 정상적으로 취소되었는지 확인할 수 있습니다.

요약

aiohttp를 사용하여 비동기 작업을 취소하는 방법을 알아보았습니다. asyncio.ensure_future()를 사용하여 취소 가능한 Task로 변환한 후, task.cancel()을 호출하여 작업을 중단할 수 있습니다. 이를 통해 웹 개발에서 비동기 작업을 효과적으로 처리할 수 있습니다.