request 세션

codakcodak·2023년 5월 3일
0

request 세션

정의:일반적으로 세션은 서버에 클라이언트별로 저장되는 정보를 의미한다.하지만 파이썬에서 request세션이란 request를 보낼때 여러 인자를 미리 저장하고 연결풀을 사용할 수 있게해주는 공간을 의미한다.

공식문서

The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3’s connection pooling. So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).

request vs session

  1. 같은 호스트로의 요청을 보낼 때

    def session_fetch(urls):
        result=[]
        with requests.Session() as session:
            for url in urls:
                with session.get(url) as response:
                    result.append(response.text)
        return result
    def fetch(urls):
        result=[requests.get(url) for url in urls]
        return result
    
    if __name__=="__main__":
    	  #같은 호스트를 여러번 보낼 경우
        urls=["https://naver.com"]*10
    
        start = time.time()
        fetch(urls)
        print("일반 요청 실행시간 :", time.time() - start,"seconds")
    
        start = time.time()
        session_fetch(urls)
        print("세션 요청 실행시간 :", time.time() - start,"seconds")
    일반 요청 실행시간 : 0.9650297164916992 seconds
    세션 요청 실행시간 : 0.5060973167419434 seconds

    같은 호스트에 대해서 여러번 요청을 보낼 때 새로운 연결을 생성하는 request보다 기존의 연결을 재사용하는 세션방식이 더 빠르다.

  2. 다른 호스트로의 요청을 보낼 때

    def session_fetch(urls):
        result=[]
        with requests.Session() as session:
            for url in urls:
                with session.get(url) as response:
                    result.append(response.text)
        return result
    def fetch(urls):
        result=[requests.get(url) for url in urls]
        return result
    
    if __name__=="__main__":
        urls=["https://naver.com",
              "https://google.com",
              "https://instagram.com",
              "https://youtube.com",
              "https://github.com",
              "https://google.com",
              "https://programmers.co.kr",
              "https://www.acmicpc.net",
              "https://solved.ac"]
        start = time.time()
        fetch(urls)
        print("일반 요청 실행시간 :", time.time() - start,"seconds")
    
        start = time.time()
        session_fetch(urls)
        print("세션 요청 실행시간 :", time.time() - start,"seconds")

    다른 호스트로 연결요청을 한다면 세션도 새로운 연결 생성해야하기에 실행속도면에서는 일반적인 방식과 비슷하다.

3.결론

  • 한 번씩만 호스트에 요청을 보낼 경우에는 코드의 간결성을 위해 일반적인 request를 사용하자.
  • 쿠키나 헤더가 미리 저장된 요청을 편리하게 쓰고 싶거나 같은 호스트에 여러번 요청을 보낸다면 세션을 사용하자.

비동기적 request 세션

import time
import asyncio

async def fetch(session,url):
    async with session.get(url) as response:
        result=await response.text()
        return result
    
async def main():
    urls=["https://naver.com","https://google.com","https://instagram.com"]*10
	#세션을 생성
    async with aiohttp.ClientSession() as session:
    	#생성한 세션을 get요청을 보내는 함수에 인자로 전달 후 한번에 요청
        result=await asyncio.gather(*[fetch(session,url) for url in urls])
        print(result)
        
if __name__=="__main__":
    start = time.time()
    asyncio.run(main())
    print("실행시간 :", time.time() - start,"seconds")
profile
숲을 보는 코더

0개의 댓글