python server-101

69
Python함께하는 서버 사이드 애플리케이션

Upload: huey-park

Post on 16-Apr-2017

577 views

Category:

Software


1 download

TRANSCRIPT

Page 1: Python server-101

Python과 함께하는서버 사이드 애플리케이션

Page 2: Python server-101

박재완[email protected]

NextFloor 풀스택 게임 프로그래머

Page 3: Python server-101

오늘 할 이야기

Page 4: Python server-101

이런 걸 만들었습니다https://github.com/HueyPark/Account-Book

Page 5: Python server-101

왜?뭔가 만들고 싶었는데...게임은 너무 어려웠습니다기획 Lv.0

Page 6: Python server-101

필요했던 기능웹 프레임워크데이터베이스 접근인증

Page 7: Python server-101

서버란 무엇인가?클라이언트에게 네트워크를 통해 서비스를

제공하는 컴퓨터 또는 프로그램-위키백과

Page 8: Python server-101

서버의 종류web serverapplication serverdatabasefile server등등등...

Page 9: Python server-101

오늘 이야기할 서버APPLICATION SERVER

Page 10: Python server-101

Application server란 무엇인가?인터넷 상에서 HTTP를 통해사용자 컴퓨터나 장치에

애플리케이션을 수행해주는 미들웨어- 위키백과

Page 11: Python server-101

Application server의 위치?Web server

|Application server

|Database server

Page 12: Python server-101

Application server는무엇으로 만들 수 있는가?

PythonPHPJavaJavascriptScala등등등...

Page 13: Python server-101

왜 Python이죠?팀에서 쓸 거 같았습니다 ㅜㅜ생산성이 좋은 거 같습니다 ;;

Page 14: Python server-101

PythonPython is a programming language that

lets you work more quickly andintegrate your systems more effectively.

Page 15: Python server-101

Python당신을 더 빨리 일할수 있게 하고

시스템과 효과적으로 통합하게 해주는프로그래밍 언어이다

Page 16: Python server-101

Python for gamesPython enabled us to create EVE Online, amassive multiplayer game, in record time.

The EVE Online server cluster runs over50,000 simultaneous players in a shared

space simulation, most of which is created inPython. The flexibilities of Python haveenabled us to quickly improve the game

experience based on player feedbacksaid Hilmar Veigar Petursson of CCP Games.

Page 17: Python server-101

Python for gamesPython은 EVE Online을 기록적인 시간에 만

들 수 있게 해주었다.서버는 5만 명 이상의 가상 플레이어를 분할

된 우주 공간에서 시뮬레이트했다.유연성 덕분에 피드백을 반영해 빠르게 게임

의 경험을 향상시킬 수 있었다.said Hilmar Veigar Petursson of CCP Games.

Page 18: Python server-101

Python 살펴보기

Page 19: Python server-101

C++int doSomething() auto a = getA(); a.do();

Page 20: Python server-101

C++int doSomething() auto a = getA(); a.do();

Page 21: Python server-101

C++int doSomething() auto a = getA(); a.do();

Page 22: Python server-101

Pythondef do_something: a = gat_a() a.do()

Page 23: Python server-101

C++if (x > 0 && x < 10) doSomething();

Page 24: Python server-101

C++if (0 < x && x < 10) doSomething();

Page 25: Python server-101

Pythonif 0 < x < 10: do_something()

Page 26: Python server-101

Hello Worldprint('Hello World')

Page 27: Python server-101

Python 첫인상간결하다

Page 28: Python server-101

PyPIthe Python Package Index

Page 29: Python server-101

Repository of so warefor the Python programming language.

Page 30: Python server-101

There are currently 75837 packages here.

Page 31: Python server-101

Python에서 관리하는 패키지 모음집

Page 32: Python server-101

이런게 됩니다pip install Flask pip install PyMySQL pip install SQLAlchemy pip install PyJWT

Page 33: Python server-101

FlaskFlask is a microframework for Python based

on Werkzeug, Jinja 2 and good intentions.

Page 34: Python server-101

문법 하나만 더!

Page 35: Python server-101

decorator 패턴주어진 상황 및 용도에 따라객체에 책임을 덧붙임

Page 36: Python server-101

decorator 패턴def decorater(func): def wrapper(): print('Hello ' + func())

return wrapper

def world(): return 'World'

helloworld = decorater(world) helloworld()

Page 37: Python server-101

decorator 패턴def decorater(func): def wrapper(): print('Hello ' + func())

return wrapper

@decorater def world(): return 'World'

world()

Page 38: Python server-101

Flask Hello Worldfrom flask import Flask app = Flask(__name__)

@app.route('/') def hello(): return 'Hello World!'

app.run()

Page 39: Python server-101

PyMySQLpure-Python MySQL client library

Page 40: Python server-101

PyMySQLimport pymysql

connection = pymysql.connect(host='localhost', user='user', password='passwd', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

with connection.cursor() as cursor: sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ('[email protected]', 'very­secret'))

connection.commit() connection.close()

Page 41: Python server-101

음... 뭔가 너무 힘듭니다

Page 42: Python server-101

SQLAlchemySQLAlchemy is the Python SQL toolkit

and Object Relational Mapper

Page 43: Python server-101

ORM은 종교전쟁 진행중...ORM의 사실과 오해

Page 44: Python server-101

ORM의 장점데이터가 객체지향적으로 추상화된다생산성이 높다이론적으로 데이터베이스 따른 의존성이 없어진다

Page 45: Python server-101

SQLAlchemy 기능소개객체 테이블 매핑세션 관리, SQL 생성테이블 생성, 삭제더 있지만 써본것만...

Page 46: Python server-101

객체 테이블 매핑from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base): __tablename__ = 'user'

user_id = Column(Integer, primary_key=True) nickname = Column(String(64), unique=True)

Page 47: Python server-101

세션 관리, 쿼리from sqlalchemy.orm import sessionmaker

Session = sessionmaker(bind=engine)

Page 48: Python server-101

세션 관리, 쿼리session = Session()

user = User(nickname='hueypark') session.add(user)

session.commit()

Page 49: Python server-101

세션 관리, 쿼리session = Session()

user = session.query(User).filter_by(name='hueypark').one() session.delete(user)

session.commit()

Page 50: Python server-101

테이블 생성, 삭제from sqlalchemy import create_engine from .models import Base

engine = create_engine('sqlite:///:memory:') Base.metadata.create_all(bind=engine)

Page 51: Python server-101

PyJWTPython library which allows you to encode

and decode JSON Web Tokens (JWT)

Page 52: Python server-101

JSON Web TokenJSON Web Tokens are an open, industry

standard method for representing claimssecurely between two parties.

Page 53: Python server-101

Token based authentication??

Page 54: Python server-101

누가 사용하나요?Facebook, Twitter, Google+, Github ...

Page 55: Python server-101

또 어떤 방법이 있죠?Session based authentication

Page 56: Python server-101

Session based authentication의 동작1. 유저 -> 서버: 로그인, 서버는 유저정보를 session에 저장2. 유저 <- 서버: session id3. 유저 -> 서버: 요청에 session id를 포함, 서버는 session에서 유저정보를 확인 후 응답

Page 57: Python server-101

Session based authentication의 문제점부하유저가 인증할 때마다 서버에 인증정보를 저장session을 유지하는 행위는 서버에 부하로 작용

확장성session 정보가 메모리에 있다면 확장성에 문제공유되는 메모리의 한계가 서버 확장의 한계로 작용

Page 58: Python server-101

Token based authentication의 동작1. 유저 -> 서버: 로그인, 서버는 유저정보를 기반으로 암호화된 token 생성

2. 유저 <- 서버: token을 클라이언트에 전달3. 유저 -> 서버: 요청에 token을 포함, 서버는 token을 통해유저정보 확인

Page 59: Python server-101

아직 잘 모르겠어요. 뭐가 다르죠?

Page 60: Python server-101

Token!토큰이 유저정보를 가지고 있습니다!

Page 61: Python server-101

Token은 세 부분으로 나누어짐HEADERPAYLOADSIGNATURE

Page 62: Python server-101

이렇게 생겼습니다eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.

eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6.

TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFO

Page 63: Python server-101

HEADER에는 암호화 알고리즘과, 타입이base64로 인코딩

"alg": "HS256", "typ": "JWT"

Page 64: Python server-101

PAYLOAD에는 데이터를 base64로 인코딩 "name": "John Doe", "admin": true

Page 65: Python server-101

SIGNATURE에 아래 결과를 base64로 인코딩HS256(HEADER + "." + PAYLOAD, secretKey)

Page 66: Python server-101

Token과 함께 해서 가능한 일서버는 상태 없음! 확장성!권한의 전달 (암호 없이!)

Facebook 글쓰기 등

Page 67: Python server-101

PyJWTfrom jwt import encode

token = encode('userid': userid, JWT_SECRET, algorithm=JWT_ALGORITHMS)

Page 68: Python server-101

PyJWTfrom jwt import decode

decoded = decode(token, JWT_SECRET, algorithms=JWT_ALGORITHMS) userid = decoded['userid']

Page 69: Python server-101

Q & A