파이썬 비동기 프로그래밍은 작업이 완료될 때까지 기다리지 않고 다른 작업을 처리할 수 있게 해, I/O 바운드 작업에서 성능 향상을 가져옴. asyncio 라이브러리와 async/await 구문을 사용하여 비동기 코드를 작성해보자.
import asyncio
import aiohttp
async def fetch_data(url):
async with aiohttp.ClientSession() as session:
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.python.org"
]
tasks = [fetch_data(url) for url in urls]
results = await asyncio.gather(*tasks)
for url, result in zip(urls, results):
print(f"Fetched {len(result)} bytes from {url}")
if __name__ == "__main__":
asyncio.run(main())
설명 :
fetch_data 함수는 웹 페이지 내용을 비동기적으로 가져옴. asyncio.gather 함수는 여러 비동기 작업을 동시에 실행하고 결과를 함. asyncio.run 함수는 비동기 메인 함수를 실행. 이 코드는 동시에 여러 웹 페이지를 가져와서 처리 시간을 단축시킴.
async/await:
async 키워드는 비동기 함수를 정의하고, await 키워드는 비동기 작업이 완료될 때까지 기다림.
aiohttp:
aiohttp는 비동기 HTTP 클라이언트/서버 라이브러리로, 비동기 웹 요청을 처리하는 데 사용.
asyncio.gather:
여러 비동기 작업을 병렬로 실행하고 결과를 리스트로 반환.
asyncio.run:
비동기 메인 함수를 실행하고 이벤트 루프를 시작.