파이썬의 @decorator
를 활용하여, HTTP 요청을 쉽게 처리하는 패키지입니다.
PyPi: https://pypi.org/p/ahttp-client
Github: https://github.com/gunyu1019/ahttp-client
예제
아래는 ahttp_client
를 이용하여 지하철 API를 불러오는 예제입니다.
station_search_with_query
위에는@request
라는 decoration(데코레이션)을 이용하여 HTTP 메소드와 주소를 사전에 정의합니다.main
함수에서station_search_with_query
메소드를 호출하면, HTTP 요청을 거친 다음,response: aiohttp.ClientResponse
파라미터에 응답 결과를 넣은 상태로 메소드가 호출됩니다.
import asyncio
import aiohttp
from ahttp_client import request, Session, Query
from typing import Annotated, Any
loop = asyncio.get_event_loop()
class MetroAPI(Session):
def __init__(self, loop: asyncio.AbstractEventLoop):
super().__init__("https://api.yhs.kr", loop=loop)
@request("GET", "/metro/station")
async def station_search_with_query(
self,
response: aiohttp.ClientResponse,
name: Annotated[str, Query]
) -> dict[str, Any]:
return await response.json()
async def main():
async with MetroAPI(loop) as client:
data = await client.station_search_with_query(name="metro-station-name")
print(len(data))
loop.run_until_complete(main())
불러오는 중...