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
같은 호스트로의 요청을 보낼 때
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보다 기존의 연결을 재사용하는 세션방식이 더 빠르다.
다른 호스트로의 요청을 보낼 때
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 세션
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")