세 가지 스타일의 웹 내려받기

매일 공부(ML)·2023년 5월 16일
0

Fluent Python

목록 보기
122/130

제어 흐름

Future를 이용한 동시성

세 가지 스타일의 웹 내려 받기

긴 지연 시간동안 CPU 클록을 낭비하지 않기 위해서 네트워크 입출력을 효율적으로 처리하라면 동시성을 이용해야하고, 네트워크에서 응답이 오는 동안 다른 일을 처리하는 것이 좋다.

순차 내려받기 스크립트

#순차 내려 받기 스크립트, 몇몇 함수는 다른 스크립트에서 재사용할 것이다.
import os
import time
import sys
import requests
 
POP20_CC = ('CN IN US ID BR PK NG BD RU JP '
 			'MK PH VN ET EG DE IR TR CD FR').split()

BASE_URL = 'http://flupy.org/data/flags'
DEST_DIR = 'downloads'/

def save_flag(img, filename):
	path = os.path.join(DEST_DIR, filename)
    with open(path,'wb') as fp:
    	fp.write(img)
        
def get_flag(cc):
	url = '{}/{cc}/{cc}/gif'.format(BASE_URL, cc=cc.lower())
    resp = requests.get(url)
    return resp.content
    
def show(text):
	print(text, end=' ')
    sys.stdout.flush()

def download_many(cc_list):
	for cc in sorted(cc_list):
    	image= get_flag(cc)
        show(cc)
        save_flag(image, cc.lower() + '.gif')
        return len(cc_list)
       
    def main(download_many):
    	t0 =time.time()
        count = download_many(POP20_CC)
        elapsed = time.time() - t0
        msg = '\n{} flags downloaded in {:.2f}s'
        print(msg.format(count,elapsed))
        
    if __name__ == '__main__':
    	main(download_many)

동시성 버전을 구현할 때 중복을 피하기 위해 하나의 라이브러리로 사용

profile
성장을 도울 아카이빙 블로그

0개의 댓글