[python] aiohttp 클라이언트의 세션 관리 방법

aiohttp는 Python의 비동기 웹 클라이언트 패키지로, HTTP 요청을 보내고 응답을 받는 것을 간편하게 처리할 수 있습니다. 이 글에서는 aiohttp의 세션 관리 기능에 대해 알아보겠습니다.

세션이란?

웹 개발에서 세션은 클라이언트와 서버 사이의 상태를 유지하는 방법입니다. 세션은 보통 로그인 상태, 장바구니 정보 등과 같이 클라이언트의 상태를 저장하기 위해 사용됩니다. aiohttp는 이러한 세션을 쉽게 관리할 수 있는 기능을 제공합니다.

aiohttp 클라이언트 세션 생성하기

import aiohttp

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get('http://example.com') as response:
            print(await response.text())

asyncio.run(main())

위의 예제에서는 aiohttp의 ClientSession 클래스를 사용하여 세션을 생성하고, ClientSession 객체를 session 변수에 할당합니다. with 문을 사용하여 세션을 사용하는 부분을 범위로 지정하고, get 메서드를 사용하여 URL에 GET 요청을 보냅니다.

세션 옵션 설정하기

import aiohttp

async def main():
    async with aiohttp.ClientSession(headers={'User-Agent': 'Mozilla/5.0'}) as session:
        async with session.get('http://example.com') as response:
            print(await response.text())

asyncio.run(main())

세션을 생성할 때 headers 매개변수를 사용하여 요청에 헤더를 추가할 수 있습니다. 위의 예제에서는 User-Agent 헤더를 설정하고 있습니다.

세션 유지하기

import aiohttp

async def main():
    jars = aiohttp.CookieJar(unsafe=True)  # 쿠키를 유지하기 위한 CookieJar 객체 생성
    async with aiohttp.ClientSession(cookie_jar=jars) as session:
        async with session.get('http://example.com') as response:
            print(await response.text())

asyncio.run(main())

세션을 생성할 때 cookie_jar 매개변수를 사용하여 쿠키를 유지할 수 있습니다. 위의 예제에서는 CookieJar 객체를 생성하고, cookie_jar 매개변수로 지정하고 있습니다.


참고문서: