Flask란?
파이썬 언어를 이용하여 웹을 구현할 수 있게 도와주는 웹 프레임워크 중 하나로 다른 프레임워크에 비해 가볍고 규칙으로부터 자유롭다.
1. 웹서버 구동
$ pip install Flask
가상환경에 Flask를 설치해줍니다.
직접 명령어로 설치하거나 파이참 에디터 File > Settings > python interpreter > Available Packages에서 설치합니다.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "hello"
def main():
app.run(debug=True, port=80)
if __name__ == '__main__':
main()
아무것도 없는 주소일 경우 @app.route('/')로 받아 hello 메서드를 실행합니다.
if __name__ == '__main__'는 모듈을 import하여 사용하는지 직접 실행하는지 구분합니다.
즉, flask 서버로 실행할 경우 name이 main이 되기 때문에 main 메서드를 실행합니다.
코드를 실행시키면 나오는 주소로 접속합니다.
hello 메서드가 실행되면서 정상적으로 접속한 것을 확인할 수 있습니다.
2. 페이지 추가
@app.route('/1')
def test1page():
return "1page ok"
@app.route('/2')
def test2page():
return "2page ok"
1과 2가 들어간 url로 접속 시 test1page와 test2page가 각각 실행되도록 코드를 추가합니다.
url에 따라 잘 출력되는 것을 확인할 수 있습니다.
3. html 출력
templates 폴더를 생성하고 안에 html 파일은 넣습니다.
from flask import Flask, render_template
@app.route('/mainHtml')
def main_html():
return render_template("main.html")
render_template 라이브러리와 html 파일을 불러올 main_html 함수를 추가합니다.
render_template으로 html 파일을 불러옵니다.