SlideShare a Scribd company logo
1 of 20
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/

More Related Content

What's hot

Mr.Robot CTF Write-Up (Korean version)
Mr.Robot CTF Write-Up (Korean version)Mr.Robot CTF Write-Up (Korean version)
Mr.Robot CTF Write-Up (Korean version)Sehan Lee
 
파이썬 스터디 15장
파이썬 스터디 15장파이썬 스터디 15장
파이썬 스터디 15장SeongHyun Ahn
 
[Kerference] 시작! 리버싱 - 김종범(KERT)
[Kerference] 시작! 리버싱 - 김종범(KERT)[Kerference] 시작! 리버싱 - 김종범(KERT)
[Kerference] 시작! 리버싱 - 김종범(KERT)NAVER D2
 
샌드박스
샌드박스샌드박스
샌드박스Baekjoon Choi
 
CTF WEB Back_END 개발기
CTF WEB Back_END 개발기CTF WEB Back_END 개발기
CTF WEB Back_END 개발기one_two_12
 
잘 알려지지 않은 숨은 진주, Winsock API - WSAPoll, Fast Loopback
잘 알려지지 않은 숨은 진주, Winsock API - WSAPoll, Fast Loopback잘 알려지지 않은 숨은 진주, Winsock API - WSAPoll, Fast Loopback
잘 알려지지 않은 숨은 진주, Winsock API - WSAPoll, Fast Loopback흥배 최
 
141103 최창원 파이썬 확장 프로그래밍
141103 최창원 파이썬 확장 프로그래밍141103 최창원 파이썬 확장 프로그래밍
141103 최창원 파이썬 확장 프로그래밍Changwon Choe
 
[2017 Incognito] 스택 구조 분석을 통한 ROP 기법의 모든 것
[2017 Incognito] 스택 구조 분석을 통한 ROP 기법의 모든 것[2017 Incognito] 스택 구조 분석을 통한 ROP 기법의 모든 것
[2017 Incognito] 스택 구조 분석을 통한 ROP 기법의 모든 것NAVER D2
 
Net debugging 3_전한별
Net debugging 3_전한별Net debugging 3_전한별
Net debugging 3_전한별Han-Byul Jeon
 
SECCON 2016 Online CTF [Memory Analysis] Write-Up (ver.korean)
SECCON 2016 Online CTF [Memory Analysis] Write-Up (ver.korean)SECCON 2016 Online CTF [Memory Analysis] Write-Up (ver.korean)
SECCON 2016 Online CTF [Memory Analysis] Write-Up (ver.korean)Sehan Lee
 
[2017 Incognito] 시스템 해킹 기법 정리
[2017 Incognito] 시스템 해킹 기법 정리[2017 Incognito] 시스템 해킹 기법 정리
[2017 Incognito] 시스템 해킹 기법 정리NAVER D2
 
[2014 CodeEngn Conference 11] 박세한 - IE 1DAY Case Study KO
[2014 CodeEngn Conference 11] 박세한 - IE 1DAY Case Study KO[2014 CodeEngn Conference 11] 박세한 - IE 1DAY Case Study KO
[2014 CodeEngn Conference 11] 박세한 - IE 1DAY Case Study KOGangSeok Lee
 
Hello c++ world
Hello c++ worldHello c++ world
Hello c++ world. Ruvendix
 
Nodejs_chapter9
Nodejs_chapter9Nodejs_chapter9
Nodejs_chapter9SH Park
 
[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석
[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석
[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석GangSeok Lee
 
BSides Delhi CTF 2018 [Never Too Late Mister (Forensics 200pts)] WriteUp
BSides Delhi CTF 2018 [Never Too Late Mister (Forensics 200pts)] WriteUpBSides Delhi CTF 2018 [Never Too Late Mister (Forensics 200pts)] WriteUp
BSides Delhi CTF 2018 [Never Too Late Mister (Forensics 200pts)] WriteUpSehan Lee
 
Codegate 2014 - Bug Hunting Challenge [Track0]
Codegate 2014 - Bug Hunting Challenge [Track0]Codegate 2014 - Bug Hunting Challenge [Track0]
Codegate 2014 - Bug Hunting Challenge [Track0]sweetchip
 
망고100 보드로 놀아보자 3
망고100 보드로 놀아보자 3망고100 보드로 놀아보자 3
망고100 보드로 놀아보자 3종인 전
 

What's hot (20)

Mr.Robot CTF Write-Up (Korean version)
Mr.Robot CTF Write-Up (Korean version)Mr.Robot CTF Write-Up (Korean version)
Mr.Robot CTF Write-Up (Korean version)
 
파이썬 스터디 15장
파이썬 스터디 15장파이썬 스터디 15장
파이썬 스터디 15장
 
[Kerference] 시작! 리버싱 - 김종범(KERT)
[Kerference] 시작! 리버싱 - 김종범(KERT)[Kerference] 시작! 리버싱 - 김종범(KERT)
[Kerference] 시작! 리버싱 - 김종범(KERT)
 
샌드박스
샌드박스샌드박스
샌드박스
 
파이썬 소개
파이썬 소개 파이썬 소개
파이썬 소개
 
CTF WEB Back_END 개발기
CTF WEB Back_END 개발기CTF WEB Back_END 개발기
CTF WEB Back_END 개발기
 
잘 알려지지 않은 숨은 진주, Winsock API - WSAPoll, Fast Loopback
잘 알려지지 않은 숨은 진주, Winsock API - WSAPoll, Fast Loopback잘 알려지지 않은 숨은 진주, Winsock API - WSAPoll, Fast Loopback
잘 알려지지 않은 숨은 진주, Winsock API - WSAPoll, Fast Loopback
 
141103 최창원 파이썬 확장 프로그래밍
141103 최창원 파이썬 확장 프로그래밍141103 최창원 파이썬 확장 프로그래밍
141103 최창원 파이썬 확장 프로그래밍
 
[2017 Incognito] 스택 구조 분석을 통한 ROP 기법의 모든 것
[2017 Incognito] 스택 구조 분석을 통한 ROP 기법의 모든 것[2017 Incognito] 스택 구조 분석을 통한 ROP 기법의 모든 것
[2017 Incognito] 스택 구조 분석을 통한 ROP 기법의 모든 것
 
Net debugging 3_전한별
Net debugging 3_전한별Net debugging 3_전한별
Net debugging 3_전한별
 
SECCON 2016 Online CTF [Memory Analysis] Write-Up (ver.korean)
SECCON 2016 Online CTF [Memory Analysis] Write-Up (ver.korean)SECCON 2016 Online CTF [Memory Analysis] Write-Up (ver.korean)
SECCON 2016 Online CTF [Memory Analysis] Write-Up (ver.korean)
 
[2017 Incognito] 시스템 해킹 기법 정리
[2017 Incognito] 시스템 해킹 기법 정리[2017 Incognito] 시스템 해킹 기법 정리
[2017 Incognito] 시스템 해킹 기법 정리
 
[2014 CodeEngn Conference 11] 박세한 - IE 1DAY Case Study KO
[2014 CodeEngn Conference 11] 박세한 - IE 1DAY Case Study KO[2014 CodeEngn Conference 11] 박세한 - IE 1DAY Case Study KO
[2014 CodeEngn Conference 11] 박세한 - IE 1DAY Case Study KO
 
Hello c++ world
Hello c++ worldHello c++ world
Hello c++ world
 
Nodejs_chapter9
Nodejs_chapter9Nodejs_chapter9
Nodejs_chapter9
 
[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석
[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석
[2014 CodeEngn Conference 11] 이경식 - 동적 추적 프레임워크를 이용한 OS X 바이너리 분석
 
BSides Delhi CTF 2018 [Never Too Late Mister (Forensics 200pts)] WriteUp
BSides Delhi CTF 2018 [Never Too Late Mister (Forensics 200pts)] WriteUpBSides Delhi CTF 2018 [Never Too Late Mister (Forensics 200pts)] WriteUp
BSides Delhi CTF 2018 [Never Too Late Mister (Forensics 200pts)] WriteUp
 
Codegate 2014 - Bug Hunting Challenge [Track0]
Codegate 2014 - Bug Hunting Challenge [Track0]Codegate 2014 - Bug Hunting Challenge [Track0]
Codegate 2014 - Bug Hunting Challenge [Track0]
 
파이선 실전공략-1
파이선 실전공략-1파이선 실전공략-1
파이선 실전공략-1
 
망고100 보드로 놀아보자 3
망고100 보드로 놀아보자 3망고100 보드로 놀아보자 3
망고100 보드로 놀아보자 3
 

Similar to 20180320 python3 async_io

Python study 1강 (오픈소스컨설팅 내부 강의)
Python study 1강 (오픈소스컨설팅 내부 강의)Python study 1강 (오픈소스컨설팅 내부 강의)
Python study 1강 (오픈소스컨설팅 내부 강의)정명훈 Jerry Jeong
 
파이썬을 배워야하는 이유 발표자료 - 김연수
파이썬을 배워야하는 이유 발표자료 - 김연수파이썬을 배워야하는 이유 발표자료 - 김연수
파이썬을 배워야하는 이유 발표자료 - 김연수Yeon Soo Kim
 
Google Protocol buffer
Google Protocol bufferGoogle Protocol buffer
Google Protocol bufferknight1128
 
[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C# 혼합 멀티플랫폼 게임 아키텍처 설계
[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C#  혼합 멀티플랫폼 게임 아키텍처 설계[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C#  혼합 멀티플랫폼 게임 아키텍처 설계
[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C# 혼합 멀티플랫폼 게임 아키텍처 설계Sungkyun Kim
 
백기선의 스프링 부트
백기선의 스프링 부트백기선의 스프링 부트
백기선의 스프링 부트Keesun Baik
 
Pycon korea - 2018 2to3 converter를 활용한 django 프로젝트 python 버전업 삽질기
Pycon korea - 2018 2to3 converter를 활용한 django 프로젝트 python 버전업 삽질기Pycon korea - 2018 2to3 converter를 활용한 django 프로젝트 python 버전업 삽질기
Pycon korea - 2018 2to3 converter를 활용한 django 프로젝트 python 버전업 삽질기Royce Nam
 
Lecture 1: Introduction to Python and TensorFlow
Lecture 1: Introduction to Python and TensorFlowLecture 1: Introduction to Python and TensorFlow
Lecture 1: Introduction to Python and TensorFlowSang Jun Lee
 
200720 바이오협회 생물정보학 파이썬 강의
200720 바이오협회 생물정보학 파이썬 강의 200720 바이오협회 생물정보학 파이썬 강의
200720 바이오협회 생물정보학 파이썬 강의 Joohyun Han
 
어플리케이션 성능 최적화 기법
어플리케이션 성능 최적화 기법어플리케이션 성능 최적화 기법
어플리케이션 성능 최적화 기법Daniel Kim
 
200718 덕성여대 생물정보학 강의 :: 생물정보학 파이썬
200718 덕성여대 생물정보학 강의 :: 생물정보학 파이썬200718 덕성여대 생물정보학 강의 :: 생물정보학 파이썬
200718 덕성여대 생물정보학 강의 :: 생물정보학 파이썬Joohyun Han
 

Similar to 20180320 python3 async_io (14)

Python study 1강 (오픈소스컨설팅 내부 강의)
Python study 1강 (오픈소스컨설팅 내부 강의)Python study 1강 (오픈소스컨설팅 내부 강의)
Python study 1강 (오픈소스컨설팅 내부 강의)
 
파이썬을 배워야하는 이유 발표자료 - 김연수
파이썬을 배워야하는 이유 발표자료 - 김연수파이썬을 배워야하는 이유 발표자료 - 김연수
파이썬을 배워야하는 이유 발표자료 - 김연수
 
Google Protocol buffer
Google Protocol bufferGoogle Protocol buffer
Google Protocol buffer
 
[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C# 혼합 멀티플랫폼 게임 아키텍처 설계
[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C#  혼합 멀티플랫폼 게임 아키텍처 설계[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C#  혼합 멀티플랫폼 게임 아키텍처 설계
[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C# 혼합 멀티플랫폼 게임 아키텍처 설계
 
백기선의 스프링 부트
백기선의 스프링 부트백기선의 스프링 부트
백기선의 스프링 부트
 
Pycon korea - 2018 2to3 converter를 활용한 django 프로젝트 python 버전업 삽질기
Pycon korea - 2018 2to3 converter를 활용한 django 프로젝트 python 버전업 삽질기Pycon korea - 2018 2to3 converter를 활용한 django 프로젝트 python 버전업 삽질기
Pycon korea - 2018 2to3 converter를 활용한 django 프로젝트 python 버전업 삽질기
 
Object C - RIP
Object C - RIPObject C - RIP
Object C - RIP
 
Lecture 1: Introduction to Python and TensorFlow
Lecture 1: Introduction to Python and TensorFlowLecture 1: Introduction to Python and TensorFlow
Lecture 1: Introduction to Python and TensorFlow
 
Spring boot DI
Spring boot DISpring boot DI
Spring boot DI
 
Python - Module
Python - ModulePython - Module
Python - Module
 
200720 바이오협회 생물정보학 파이썬 강의
200720 바이오협회 생물정보학 파이썬 강의 200720 바이오협회 생물정보학 파이썬 강의
200720 바이오협회 생물정보학 파이썬 강의
 
어플리케이션 성능 최적화 기법
어플리케이션 성능 최적화 기법어플리케이션 성능 최적화 기법
어플리케이션 성능 최적화 기법
 
08 모듈
08 모듈08 모듈
08 모듈
 
200718 덕성여대 생물정보학 강의 :: 생물정보학 파이썬
200718 덕성여대 생물정보학 강의 :: 생물정보학 파이썬200718 덕성여대 생물정보학 강의 :: 생물정보학 파이썬
200718 덕성여대 생물정보학 강의 :: 생물정보학 파이썬
 

20180320 python3 async_io

  • 1. Python3 and AsyncIO Sharing about '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
  • 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/
  • 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의 증가에 영향받지 않음.
  • 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 필요.