통신관련 동기 처리
import requests
import time
def request_site(url, session):
# checking session
# print(session)
# print(session.headers)
with session.get(url) as response:
print(f"[Read contents: {len(response.content)}, Status code: {response.status_code} from {url}")
def request_all_site(urls):
with requests.Session() as session:
for url in urls:
request_site(url, session)
def main():
urls = [
"https://www.jython.org",
"https://www.naver.com",
"https://realpython.com/"
] * 3
start_time = time.time()
request_all_site(urls)
duration = time.time() - start_time
print(f"Download {len(urls)} sites in {duration} seconds")
if __name__=='__main__':
main()
--------------------------------------[result]
[Read contents: 10394, Status code: 200 from https://www.jython.org
[Read contents: 213343, Status code: 200 from https://www.naver.com
[Read contents: 40220, Status code: 200 from https://realpython.com/
[Read contents: 10394, Status code: 200 from https://www.jython.org
[Read contents: 212180, Status code: 200 from https://www.naver.com
[Read contents: 40219, Status code: 200 from https://realpython.com/
[Read contents: 10394, Status code: 200 from https://www.jython.org
[Read contents: 190490, Status code: 200 from https://www.naver.com
[Read contents: 40221, Status code: 200 from https://realpython.com/
Download 9 sites in 4.343730449676514 seconds
'Python > Advanced' 카테고리의 다른 글
[Python] I/O Bound(2) - Multiproecessing (0) | 2021.05.20 |
---|---|
[Python] I/O Bound(2) - Multithreading (0) | 2021.05.20 |
[Python] Blocking vs Non-Blocking, Sync vs Async (0) | 2021.05.19 |
[Python] Multiprocessing(5) - Queue, Pipe (0) | 2021.05.19 |
[Python] Multiprocessing(4) - Sharing state (0) | 2021.05.19 |