python server-101
TRANSCRIPT
Python과 함께하는서버 사이드 애플리케이션
NextFloor 풀스택 게임 프로그래머
오늘 할 이야기
이런 걸 만들었습니다https://github.com/HueyPark/Account-Book
왜?뭔가 만들고 싶었는데...게임은 너무 어려웠습니다기획 Lv.0
필요했던 기능웹 프레임워크데이터베이스 접근인증
서버란 무엇인가?클라이언트에게 네트워크를 통해 서비스를
제공하는 컴퓨터 또는 프로그램-위키백과
서버의 종류web serverapplication serverdatabasefile server등등등...
오늘 이야기할 서버APPLICATION SERVER
Application server란 무엇인가?인터넷 상에서 HTTP를 통해사용자 컴퓨터나 장치에
애플리케이션을 수행해주는 미들웨어- 위키백과
Application server의 위치?Web server
|Application server
|Database server
Application server는무엇으로 만들 수 있는가?
PythonPHPJavaJavascriptScala등등등...
왜 Python이죠?팀에서 쓸 거 같았습니다 ㅜㅜ생산성이 좋은 거 같습니다 ;;
PythonPython is a programming language that
lets you work more quickly andintegrate your systems more effectively.
Python당신을 더 빨리 일할수 있게 하고
시스템과 효과적으로 통합하게 해주는프로그래밍 언어이다
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.
Python for gamesPython은 EVE Online을 기록적인 시간에 만
들 수 있게 해주었다.서버는 5만 명 이상의 가상 플레이어를 분할
된 우주 공간에서 시뮬레이트했다.유연성 덕분에 피드백을 반영해 빠르게 게임
의 경험을 향상시킬 수 있었다.said Hilmar Veigar Petursson of CCP Games.
Python 살펴보기
C++int doSomething() auto a = getA(); a.do();
C++int doSomething() auto a = getA(); a.do();
C++int doSomething() auto a = getA(); a.do();
Pythondef do_something: a = gat_a() a.do()
C++if (x > 0 && x < 10) doSomething();
C++if (0 < x && x < 10) doSomething();
Pythonif 0 < x < 10: do_something()
Hello Worldprint('Hello World')
Python 첫인상간결하다
PyPIthe Python Package Index
Repository of so warefor the Python programming language.
There are currently 75837 packages here.
Python에서 관리하는 패키지 모음집
이런게 됩니다pip install Flask pip install PyMySQL pip install SQLAlchemy pip install PyJWT
FlaskFlask is a microframework for Python based
on Werkzeug, Jinja 2 and good intentions.
문법 하나만 더!
decorator 패턴주어진 상황 및 용도에 따라객체에 책임을 덧붙임
decorator 패턴def decorater(func): def wrapper(): print('Hello ' + func())
return wrapper
def world(): return 'World'
helloworld = decorater(world) helloworld()
decorator 패턴def decorater(func): def wrapper(): print('Hello ' + func())
return wrapper
@decorater def world(): return 'World'
world()
Flask Hello Worldfrom flask import Flask app = Flask(__name__)
@app.route('/') def hello(): return 'Hello World!'
app.run()
PyMySQLpure-Python MySQL client library
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]', 'verysecret'))
connection.commit() connection.close()
음... 뭔가 너무 힘듭니다
SQLAlchemySQLAlchemy is the Python SQL toolkit
and Object Relational Mapper
ORM은 종교전쟁 진행중...ORM의 사실과 오해
ORM의 장점데이터가 객체지향적으로 추상화된다생산성이 높다이론적으로 데이터베이스 따른 의존성이 없어진다
SQLAlchemy 기능소개객체 테이블 매핑세션 관리, SQL 생성테이블 생성, 삭제더 있지만 써본것만...
객체 테이블 매핑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)
세션 관리, 쿼리from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
세션 관리, 쿼리session = Session()
user = User(nickname='hueypark') session.add(user)
session.commit()
세션 관리, 쿼리session = Session()
user = session.query(User).filter_by(name='hueypark').one() session.delete(user)
session.commit()
테이블 생성, 삭제from sqlalchemy import create_engine from .models import Base
engine = create_engine('sqlite:///:memory:') Base.metadata.create_all(bind=engine)
PyJWTPython library which allows you to encode
and decode JSON Web Tokens (JWT)
JSON Web TokenJSON Web Tokens are an open, industry
standard method for representing claimssecurely between two parties.
Token based authentication??
누가 사용하나요?Facebook, Twitter, Google+, Github ...
또 어떤 방법이 있죠?Session based authentication
Session based authentication의 동작1. 유저 -> 서버: 로그인, 서버는 유저정보를 session에 저장2. 유저 <- 서버: session id3. 유저 -> 서버: 요청에 session id를 포함, 서버는 session에서 유저정보를 확인 후 응답
Session based authentication의 문제점부하유저가 인증할 때마다 서버에 인증정보를 저장session을 유지하는 행위는 서버에 부하로 작용
확장성session 정보가 메모리에 있다면 확장성에 문제공유되는 메모리의 한계가 서버 확장의 한계로 작용
Token based authentication의 동작1. 유저 -> 서버: 로그인, 서버는 유저정보를 기반으로 암호화된 token 생성
2. 유저 <- 서버: token을 클라이언트에 전달3. 유저 -> 서버: 요청에 token을 포함, 서버는 token을 통해유저정보 확인
아직 잘 모르겠어요. 뭐가 다르죠?
Token!토큰이 유저정보를 가지고 있습니다!
Token은 세 부분으로 나누어짐HEADERPAYLOADSIGNATURE
이렇게 생겼습니다eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6.
TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFO
HEADER에는 암호화 알고리즘과, 타입이base64로 인코딩
"alg": "HS256", "typ": "JWT"
PAYLOAD에는 데이터를 base64로 인코딩 "name": "John Doe", "admin": true
SIGNATURE에 아래 결과를 base64로 인코딩HS256(HEADER + "." + PAYLOAD, secretKey)
Token과 함께 해서 가능한 일서버는 상태 없음! 확장성!권한의 전달 (암호 없이!)
Facebook 글쓰기 등
PyJWTfrom jwt import encode
token = encode('userid': userid, JWT_SECRET, algorithm=JWT_ALGORITHMS)
PyJWTfrom jwt import decode
decoded = decode(token, JWT_SECRET, algorithms=JWT_ALGORITHMS) userid = decoded['userid']
Q & A