Languages/python

[PYTHON] Flask(01) 설치부터 기본연동

뱅타 2021. 3. 23. 19:34
  • 설치하기
$conda install flask
$pip install flask

둘 중 하나로 flask를 설치.

아나콘다를 설치 하였다면 위에있는 콘다 명령어를 우선적으로 사용하는 것을 추천. 후에 코드 충돌 우려가 있기 때문

1. 기본적인 서버 열기

from flask import Flask

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run(host="127.0.0.1", port='80')

실행 후 본인이 사용하는 인터넷(chrome / IE) 등을 실행 시킨 후

localhost를 입력한다.

결과

2. html 연동하기

반드시 폴더 배치를 따라야 한다.

프로젝트명 / 폴더1 / templates

폴더1 에는 해당 .py파일이 속해 있어야 하며 연결할 html파일은

templates 폴더에 반드시 있어야 한다.

이렇게 배치하지 않을 시 경로를 찾지 못함.

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

3. parameter(파라미터) 받기

1. get방식

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/', methods=['get'])
def hello():
    param = request.args.get("a", "defaultValue")
   
    return 'Hello world ' + param

if __name__ == '__main__':
    app.run(host="127.0.0.1", port='80')

@app.route('/', methods=['get'])

여기의 methods는 작성하지 않아도 상관없다. 적어주지 않으면 get방식을 기본방식으로 여기기 때문이다.

def hello(): param = request.args.get("a", "defaultValue")

이 부분의 "defaultValue"의 경우 첫 화면 실행 시 parameter값이 없을 수 있기 때문에 기본값을 주어준 것이다.

2. post방식


@app.route('/post', methods=['POST'])
def post():
    value = request.form['test']
    return value

get - request.args.get()

post - resquest.form[]

둘의 파라미터 받는 차이점을 알아두자.

from flask import Flask, render_template, request

app = Flask(__name__)

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

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

@app.route('/post', methods=['POST'])
def post():
    value = request.form['test']
    return value

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

M- Model - vo

V - View - jsp

C - Controller - flask

  • html에서 flask 데이터 가져오는 방법(파라미터)
@app.route('/')
def hello():
    hello = "hello world"
    return render_template('hello.html', hello = hello)

return render_template('hello.html', hello = hello) 이렇게

경로 설정, 넘길 변수 추가.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	im fine thank you
	{{hello}}
</body>
</html>

html에서 hello 불러오기

{{}} 이런 문법을 jinja2라고 부른다.

https://jinja.palletsprojects.com/en/2.11.x/templates/#builtin-filters

from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
def hello():
    list = ["홍길동", "전우치", "김도윤"]
    return render_template('hello.html', list=list)

if __name__ == '__main__':
    app.run(host="127.0.0.1", port='80')

.py에 이렇게 작성 후

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	im fine thank you
	<select>
		{% for item in list %}
		<option>{{item}}</option>
		{% endfor %}
	</select>
</body>
</html>

.html 파일에 이렇게 작성후 실행시켜보면

결과

이렇게 잘 나오는걸 알 수 있다.

728x90
반응형