이번 포스트에서는 Python의 aiohttp
라이브러리를 사용하여 비동기 HTTP 요청을 보내는 방법에 대해 살펴보겠습니다. aiohttp
는 비동기 웹 애플리케이션을 구축하기 위한 강력한 도구로, asyncio 라이브러리와 함께 사용될 수 있습니다.
1. aiohttp
설치
먼저, aiohttp
를 설치해야 합니다. 다음 명령을 사용하여 설치할 수 있습니다:
pip install aiohttp
2. 비동기 HTTP 요청 보내기
aiohttp
를 사용하여 비동기 HTTP 요청을 보내는 간단한 예제를 살펴보겠습니다. 다음 코드를 참고하세요:
import aiohttp
import asyncio
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:
html = await fetch(session, 'https://www.example.com')
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
위 코드에서 fetch
함수는 주어진 URL로 비동기 GET 요청을 보내고, 응답을 받은 후에는 응답 본문을 반환합니다. main
함수에서는 ClientSession
을 사용하여 HTTP 요청을 보내고, fetch
함수를 사용하여 응답을 받은 HTML을 출력합니다. 마지막으로, event_loop
를 실행하여 프로그램을 실행합니다.
3. 비동기 요청 동시에 보내기
aiohttp
를 사용하면 여러 개의 비동기 요청을 동시에 보낼 수도 있습니다. asyncio.gather
함수를 사용하여 여러 개의 비동기 작업을 하나로 묶을 수 있습니다. 다음 예제를 참고하세요:
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = ['https://www.example.com', 'https://www.google.com', 'https://www.github.com']
async with aiohttp.ClientSession() as session:
tasks = [fetch(session, url) for url in urls]
responses = await asyncio.gather(*tasks)
for response in responses:
print(response)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
위 코드에서 urls
리스트에 여러 개의 URL을 저장하고, fetch
함수를 각 URL에 대해 호출하여 비동기 요청을 보냅니다. asyncio.gather
함수를 사용하여 모든 비동기 작업을 하나로 묶은 후에는 responses
리스트에 각각의 응답이 저장됩니다. 마지막으로, 각 응답을 출력합니다.
aiohttp
를 사용하여 비동기 HTTP 요청을 보내는 방법에 대해 알아보았습니다. 이를 통해 효율적이고 빠른 웹 애플리케이션을 개발할 수 있습니다.