오늘은 http통신을 비동기로 실행해 보겠습니다.
이 방법을 사용하게 된 이유는
카카오 i클라우드에서 서비스 중인 맞춤법 검사기 API를 사용하여
빠르게 텍스트를 전처리 하기 위해 사용하였습니다.
pip install aiohttp
import aiohttp
import asyncio
URL = "https://my-api-url"
HEADERS = {
"x-api-key": "my_api_key",
"Content-Type": "application/json"
}
async def call(text):
data = {"query": text, "help", "on"}
# 전달 받은 session으로 async 처리
async with aiohttp.ClientSession().post(
URL,
headers=HEADERS,
data=data
) as response:
if response.status == 200:
""" aiohttp의 요청은 기본 적으로 2mb로 제한됨
2mb보다 큰 데이터를 받아 올 경우
iter_chunked(chunk_size)를 활용하여
스트림을 받아 와야 함
"""
chunks = [data async for data in response.content.iter_chunked(2048)]
return reduce(lambda x,y: x+y, chunks).decode("utf-8")
async def main(text):
futures = [asyncio.ensure_future(call(text)) for _ in range(0, 10)]
result = await asyncio.gather(*futures)
return result
text1 = "아버지가방에들어가시다1"
text2 = "아버지가방에들어가시다2"
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(main(text1), main(text2)))