Flask 설치

pip을 이용해서 설치한다. 난 다음과 같이 Pycharm의 패키지매니저(Ctrl+Alt+s)를 사용해서 설치했다.

Flask Install

HelloWorld 구동하기

설치가 끝났다면 HelloWorld를 구동해보자. 아주 간단하다. Flask 앱의 메인이 될 파이썬 파일을 하나 만들고 대략 다음과 같은 식으로 작성한다.

# flask 임포트 
from flask import Flask
app = Flask(__name__)

# 라우팅 작성 
@app.route('/')
def hello():
    # 향후에는 DB에서 데이터 조회하는 등 처리한 후 결과 리턴 (혹은 결과를 렌더링하는 페이지 리턴) 하는 식으로 개선할 수 있다. 
    return "HelloWorld!"

# 웹 어플리케이션 실행 
# debug모드로 실행하면 코드 수정사항이 바로 반영된다. HTML 페이지 수정결과등을 바로바로 확인할 수 있어서 개발중에는 debug모드로 실행하면 좋다. 
app.run(host="localhost", port=5001, debug=True)

어플리케이션 실행 후 웹 브라우저로 확인한 모습 Flask Hello World

HTML 페이지 연동

Flask 앱 파이썬 파일이 위치한 경로에 templates 폴더를 만든다. (HTML 페이지는 기본적으로 templates 폴더의 것을 렌더링하도록 되어 있다.) index.html 파일을 생성한다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Hello World in HTML File!
</body>
</html>

그리고 Flask 앱 코드는 다음과 같이 수정한다.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def hello():
    return render_template("index.html")

app.run(host="localhost", port=5001, debug=True)

웹브라우저로 접속해서 확인해본다.

Flask Hello World

성공이다!

Jinja 템플릿 엔진

파이썬의 데이터를 HTML 페이지에 출력해주기 위해서는 템플릿 엔진이 필요하다. Flask는 Jinja 라는 템플릿 엔진을 사용한다.

템플릿엔진에 데이터를 전달하기

데이터를 render_template함수의 추가 파라메터로 전달한다. 데이터는 여기에서 얻어왔다.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def hello():
    print("Hello")
    student_list = [
        {"name": "Sandrine", "score": 100},
        {"name": "Gergeley", "score": 87},
        {"name": "Frieda", "score": 92},
        {"name": "Fritz", "score": 40},
        {"name": "Sirius", "score": 75},
    ]
    return render_template("index.html", students=student_list)

app.run(host="localhost", port=5001, debug=True)

HTML 페이지에서는 다음과 같은 식으로 데이터를 출력한다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Hello World in HTML File!
<table>

</table>
</body>
</html>

결과 페이지는 다음과 같다.

Flask Hello World with Data

GET 메서드 파라메터

  • methods를 지정하지 않아도 기본적으로 GET메서드로 동작한다.
  • GET 메서드의 파라메터는 다음과 같이 request.args.get로 얻어올 수 있다.
  • 출처: https://stackoverflow.com/questions/24892035/how-can-i-get-the-named-parameters-from-a-url-using-flask
from flask import request

@app.route('/login')
def login():
    username = request.args.get('username')
    password = request.args.get('password')

POST 메서드 파라메터

  • 다음과 같이 methods를 POST로 지정한다.
  • POST 메서드 파라메터는 request.form.get으로 얻어올 수 있다.
from flask import request

@app.route('/login',methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')