Python3 and AsyncIO
Sharing about 'experience of applying'
2018.03.20
Park Jae Hong
Contents
1. Python 3
a. 3.6으로 시작
b. 적용 순서
c. 주요 문법 변화
d. 이슈들…
e. 얼마 남지 않았다
2. AsyncIO
a. 소개
b. 일반 예제
c. 적용 예제
d. 성능 차이
e. 업무 적용 사례
3. Summary
a. Python3
b. AsyncIO
1.Python 3
1. Python3 - a. 3.6으로 시작
● async def와 await는 파이썬 3.5에서 추가되었음
● 따라서 그 이하 버전에서는 사용할 수 없음
● 파이썬 3.4에서는 @asyncio.coroutine 데코레이터로 네이티브 코루틴을 생성
● 3.6(stable version)으로 시작하는것을 추천
1. Python3 - b. 적용 순서
1. Python 3.6 Download(https://www.python.org/)
2. Read Readme
a. configure
b. make
c. make test
d. sudo make install
3. install python package
a. using pip3.6
1. Python3 - c. 주요 문법 변화
Python 2 Python 3
int 나눈 결과 float print( 1/2 ) # 0
print( type(1/2) ) # <type 'int'>
print( 1/2 ) # 0.5
print( type(1/2) ) # <class 'float'>
print문 괄호 필수 print( 'hello' ) # hello
print 'hello' # hello
print( 'hello' ) # hello
print 'hello' # Error! invalid syntax
str과 unicode 통일 print( type('hello') ) # <type 'str'>
print( type(u'hello') ) # <type 'unicode'>
print( type('hello') ) # <class 'str'>
print( type(u'hello') ) # <class 'str'>
long은 int로 통일 print( 2**30 ) # 1073741824
print( type(2**30) ) # <type 'int'>
print( 2**100 ) #
1267650600228229401496703205376
print( type(2**100) ) # <type 'long'>
print( 2**30 ) # 1073741824
print( type(2**30) ) # <class 'int'>
print( 2**100 ) #
1267650600228229401496703205376
print( type(2**100) ) # <class 'int'>
1. Python3 - d. 이슈들...
1. int 나눈결과 float: 쉬움
2. print문 괄호 필수: 쉬움
3. str과 unicode 통일: 경우에 따라 어려움
4. long과 int 통일: 쉬움
5. dictionary의 iter~, view~ 시리즈 삭제: 쉬움
6. 외부 package들의 호환성: 경우에 따라 귀찮음
7. except Exception, e: -> except Exception as e: 쉬움
1. Python3 - e. 얼마 남지 않았다
● https://pythonclock.org/
2.AsyncIO
2. AsyncIO - a. 소개
2. AsyncIO - b. 일반 예제
# Example 1: synchronous requests
import requests
num_requests = 20
responses = [
requests.get('http://example.org/')
for i in range(num_requests)
]
2. AsyncIO - c. 적용 예제
# Example 2: asynchronous requests
import asyncio
import requests
async def main():
loop = asyncio.get_event_loop()
futures = [
loop.run_in_executor(
None,
requests.get,
'http://example.org/'
)
for i in range(20)
]
for response in await asyncio.gather(*futures):
pass
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
2. AsyncIO - d. 성능 차이
2. AsyncIO - e. 업무 적용 사례
loop = asyncio.get_event_loop() # 이벤트 루프를 얻음
try_cnc_nodedata = loop.run_until_complete(cnc_nodedata.get_cnc_data(ACCOUNT_INFO, ACCOUNT_DOMAIN_MAP,
DOMAIN_INFO, start_datetime, end_datetime, req_date, headers, try_cnc_nodedata))
loop.close()
==========
def do_post_req():
return requests.post(url, data=json_data, headers=_headers, auth=(_id, _pwd), timeout=CONFIG["CNC_API_TIMEOUT"])
loop = asyncio.get_event_loop()
res = await loop.run_in_executor(None, do_post_req)
2. AsyncIO - e. 업무 적용 사례(cont.)
● AsyncIO 적용 전
○ 270초 정도 소요.
○ domain의 증가에 따라 소요 시간 증가
● AsyncIO 적용 후
○ 60초 정도 소요
○ domain의 증가에 영향받지 않음.
3.Summary
3. Summary - a. Python3
● Python은 v3를 써야만 한다.
● v2 -> v3 는 몇몇 경우를 제외하고는 그리 어렵지 않다.
● 지금 바로 넘어가세요~
3. Summary - b. AsyncIO
● IO비중이 높다면 눈에 띄는 성능 개선!
● 그동안 무시해왔던 Python의 Multi Thread를 적극 활용.
● async, await, event loop, native coroutine 등의 개념은 study 필요.
The End
reference
● https://zetawiki.com/wiki/Python_%EB%B2%84%EC%A0%84_2%EC%99%80_3
_%EC%B0%A8%EC%9D%B4
● https://dojang.io/mod/page/view.php?id=1167
● http://skipperkongen.dk/2016/09/09/easy-parallel-http-requests-with-python-
and-asyncio/

20180320 python3 async_io

  • 1.
    Python3 and AsyncIO Sharingabout 'experience of applying' 2018.03.20 Park Jae Hong
  • 2.
    Contents 1. Python 3 a.3.6으로 시작 b. 적용 순서 c. 주요 문법 변화 d. 이슈들… e. 얼마 남지 않았다 2. AsyncIO a. 소개 b. 일반 예제 c. 적용 예제 d. 성능 차이 e. 업무 적용 사례 3. Summary a. Python3 b. AsyncIO
  • 3.
  • 4.
    1. Python3 -a. 3.6으로 시작 ● async def와 await는 파이썬 3.5에서 추가되었음 ● 따라서 그 이하 버전에서는 사용할 수 없음 ● 파이썬 3.4에서는 @asyncio.coroutine 데코레이터로 네이티브 코루틴을 생성 ● 3.6(stable version)으로 시작하는것을 추천
  • 5.
    1. Python3 -b. 적용 순서 1. Python 3.6 Download(https://www.python.org/) 2. Read Readme a. configure b. make c. make test d. sudo make install 3. install python package a. using pip3.6
  • 6.
    1. Python3 -c. 주요 문법 변화 Python 2 Python 3 int 나눈 결과 float print( 1/2 ) # 0 print( type(1/2) ) # <type 'int'> print( 1/2 ) # 0.5 print( type(1/2) ) # <class 'float'> print문 괄호 필수 print( 'hello' ) # hello print 'hello' # hello print( 'hello' ) # hello print 'hello' # Error! invalid syntax str과 unicode 통일 print( type('hello') ) # <type 'str'> print( type(u'hello') ) # <type 'unicode'> print( type('hello') ) # <class 'str'> print( type(u'hello') ) # <class 'str'> long은 int로 통일 print( 2**30 ) # 1073741824 print( type(2**30) ) # <type 'int'> print( 2**100 ) # 1267650600228229401496703205376 print( type(2**100) ) # <type 'long'> print( 2**30 ) # 1073741824 print( type(2**30) ) # <class 'int'> print( 2**100 ) # 1267650600228229401496703205376 print( type(2**100) ) # <class 'int'>
  • 7.
    1. Python3 -d. 이슈들... 1. int 나눈결과 float: 쉬움 2. print문 괄호 필수: 쉬움 3. str과 unicode 통일: 경우에 따라 어려움 4. long과 int 통일: 쉬움 5. dictionary의 iter~, view~ 시리즈 삭제: 쉬움 6. 외부 package들의 호환성: 경우에 따라 귀찮음 7. except Exception, e: -> except Exception as e: 쉬움
  • 8.
    1. Python3 -e. 얼마 남지 않았다 ● https://pythonclock.org/
  • 9.
  • 10.
    2. AsyncIO -a. 소개
  • 11.
    2. AsyncIO -b. 일반 예제 # Example 1: synchronous requests import requests num_requests = 20 responses = [ requests.get('http://example.org/') for i in range(num_requests) ]
  • 12.
    2. AsyncIO -c. 적용 예제 # Example 2: asynchronous requests import asyncio import requests async def main(): loop = asyncio.get_event_loop() futures = [ loop.run_in_executor( None, requests.get, 'http://example.org/' ) for i in range(20) ] for response in await asyncio.gather(*futures): pass loop = asyncio.get_event_loop() loop.run_until_complete(main())
  • 13.
    2. AsyncIO -d. 성능 차이
  • 14.
    2. AsyncIO -e. 업무 적용 사례 loop = asyncio.get_event_loop() # 이벤트 루프를 얻음 try_cnc_nodedata = loop.run_until_complete(cnc_nodedata.get_cnc_data(ACCOUNT_INFO, ACCOUNT_DOMAIN_MAP, DOMAIN_INFO, start_datetime, end_datetime, req_date, headers, try_cnc_nodedata)) loop.close() ========== def do_post_req(): return requests.post(url, data=json_data, headers=_headers, auth=(_id, _pwd), timeout=CONFIG["CNC_API_TIMEOUT"]) loop = asyncio.get_event_loop() res = await loop.run_in_executor(None, do_post_req)
  • 15.
    2. AsyncIO -e. 업무 적용 사례(cont.) ● AsyncIO 적용 전 ○ 270초 정도 소요. ○ domain의 증가에 따라 소요 시간 증가 ● AsyncIO 적용 후 ○ 60초 정도 소요 ○ domain의 증가에 영향받지 않음.
  • 16.
  • 17.
    3. Summary -a. Python3 ● Python은 v3를 써야만 한다. ● v2 -> v3 는 몇몇 경우를 제외하고는 그리 어렵지 않다. ● 지금 바로 넘어가세요~
  • 18.
    3. Summary -b. AsyncIO ● IO비중이 높다면 눈에 띄는 성능 개선! ● 그동안 무시해왔던 Python의 Multi Thread를 적극 활용. ● async, await, event loop, native coroutine 등의 개념은 study 필요.
  • 19.
  • 20.