[python] 파이썬 웹 클라이언트에서 비동기적으로 동시 다중 요청을 처리하는 방법은 무엇인가요?
아래는 비동기 웹 클라이언트를 사용하여 동시에 여러 개의 요청을 처리하는 예제 코드입니다.
import asyncio
import aiohttp
async def fetch_url(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = ['http://example.com', 'http://example.org', 'http://example.net']
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks)
for result in results:
print(result)
if __name__ == '__main__':
asyncio.run(main())
이 예제에서는 asyncio
를 사용하여 비동기 웹 요청을 한꺼번에 처리하고, aiohttp
를 사용하여 웹 클라이언트를 생성합니다. fetch_url
함수는 각 URL에 대한 비동기 요청을 수행하고, asyncio.gather
를 사용하여 모든 요청이 완료될 때까지 기다린 후 결과를 처리합니다.
asyncio
와 aiohttp
에 대한 자세한 내용은 아래 레퍼런스를 참고하시기 바랍니다.
- asyncio 공식 문서: Python asyncio 공식 문서
- aiohttp 공식 문서: aiohttp 공식 문서