본문 바로가기

CODING/Python

[Python] Flask를 이용한 웹 어플리케이션 만들기 (flask 설치 및 사용법)

 Flask

Flask란 웹 어플리케이션 개발을 위한 파이썬 프레임워크이다.

  • Flask 설치
pip install Flask

 

 

  • 예제

기본적인 flask의 사용법은 아래와 같다. Hello Wolrd!를 출력하는 단순한 웹 애플리케이션을 보여준다.

from flask import Flask
app = Flask(__name__)   # app 라는 변수에 Flask(__name__)을 저장한다.

@app.route("/")   # http://localhost:5000/를 가리킨다. 플라스크에서는 기본적으로 5000번 포트를 사용하기 때문
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

@app.route() 데코레이터 밑에는 가르키는 주소에 접근했을 때 반환해줄 함수가 정의되어 있다.

 

 

 render_template

render_template 함수는 flask에서 제공하는 함수로, templates에 저장된 html을 불러올때 사용한다.

@app.route('/')
def hi():
    return render_template('hi.html')

 

 

 

< example>

from flask import Flask, render_template

templates_route = 'venv/templates'
app = Flask(__name__)

@app.route('/')
def hi():
    return render_template('hi.html')

app.run()