PHpullh
학습 라이브러리/Python/aiohttp 비동기 HTTP

PYTHON · 비동기

aiohttp 비동기 HTTP

aiohttp로 비동기 HTTP 클라이언트를 구현하여 동시에 여러 요청을 처리합니다.

비동기중급aiohttpHTTP비동기동시 요청

핵심 설명

aiohttp로 비동기 HTTP 클라이언트를 구현하여 동시에 여러 요청을 처리합니다.

Python code

import asyncio

# aiohttp 없이 시뮬레이션
async def fake_fetch(url: str, delay: float = 1.0) -> dict:
    """HTTP 요청 시뮬레이션"""
    await asyncio.sleep(delay)
    return {"url": url, "status": 200, "body": f"응답: {url}"}

async def fetch_all(urls: list[str]) -> list[dict]:
    """여러 URL을 동시에 요청"""
    tasks = [fake_fetch(url, 0.5) for url in urls]
    return await asyncio.gather(*tasks)

async def fetch_with_limit(urls, max_concurrent=3):
    """동시 요청 수 제한"""
    semaphore = asyncio.Semaphore(max_concurrent)

    async def limited_fetch(url):
        async with semaphore:
            return await fake_fetch(url, 1.0)

    return await asyncio.gather(
        *[limited_fetch(url) for url in urls]
    )

async def main():
    urls = [f"https://api.example.com/item/{i}" for i in range(5)]

    import time
    start = time.perf_counter()
    results = await fetch_all(urls)
    elapsed = time.perf_counter() - start
    print(f"{len(results)}개 요청 완료: {elapsed:.2f}초")

    start = time.perf_counter()
    results = await fetch_with_limit(urls, max_concurrent=2)
    elapsed = time.perf_counter() - start
    print(f"제한 요청 완료: {elapsed:.2f}초")

asyncio.run(main())

학습 팁

실제 사용 시 pip install aiohttpaiohttp.ClientSession을 사용하세요. 세션을 재사용하면 연결 풀링 혜택을 받습니다.

주의할 점

aiohttp.ClientSessionasync with로 관리하지 않으면 연결이 제대로 닫히지 않아 리소스 누수가 발생합니다.

자주 묻는 질문

aiohttp 비동기 HTTP란 무엇인가요?

aiohttp 로 비동기 HTTP 클라이언트를 구현하여 동시에 여러 요청을 처리합니다.

aiohttp 비동기 HTTP 학습 시 주의할 점은 무엇인가요?

aiohttp.ClientSession 을 async with 로 관리하지 않으면 연결이 제대로 닫히지 않아 리소스 누수가 발생합니다.