본문 바로가기

Python/Advanced

[Python] I/O Bound(1) - Synchronous

통신관련 동기 처리

 

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