플라스크 : 핵심 모듈은 가볍고 단순하지만 다른 라이브러리들과 연결하여 쉽게 확장할 수 있어 마이크로프레임워크라고 함
☑️플라스크 설치하기☑️
conda install flask
첫 번째 애플리케이션 - 이름만 입력하는 폼 필드 하나만 가진 간단한 웹 페이지
☑️디렉터리 구조 만들기☑️
1st_flask_app_1/
app.py
templates/
first_app.html
☑️app.py 파일 내용 살펴보기☑️
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('first_app.html')
if __name__ == '__main__':
app.run(debug=True)
☑️first_app.html 파일 내용 살펴보기☑️
<!doctype html>
<html>
<head>
<title>첫 번째 애플리케이션</title>
</head>
<body>
<div>
와우, 첫 번째 플라스크 웹 애플리케이션입니다!
</div>
</body>
</html>
☑️로컬에서 웹 애플리케이션 실행하기☑️
python app.py
Running on http://127.0.0.1:5000/
WTForms 라이브러리를 사용하여 폼 요소 추가하기
☑️WTForms 라이브러리 설치하기☑️
conda install wtforms
☑️디렉터리 구조 셋팅하기☑️
1st_flask_app_2/
app.py
static/
style.css
templates/
_formhelpers.html
first_app.html
hello.html
☑️수정된 app.py 파일 내용 살펴보기☑️
from flask import Flask, render_template, request
from wtforms import Form, TextAreaField, validators
app = Flask(__name__)
class HelloForm(Form):
sayhello = TextAreaField('',[validators.DataRequired()])
@app.route('/')
def index():
form = HelloForm(request.form)
return render_template('first_app.html', form=form)
@app.route('/hello', methods=['POST'])
def hello():
form = HelloForm(request.form)
if request.method == 'POST' and form.validate():
name = request.form['sayhello']
return render_template('hello.html', name=name)
return render_template('first_app.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
☑️진자2 템플릿 엔진을 사용하여 매크로 구현하기☑️
{% macro render_field(field) %}
<dt>{{ field.label }}
<dd>{{ field(**kwargs)|safe }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</dd>
</dt>
{% endmacro %}
☑️CSS로 스타일 추가☑️
body {
font-size: 2em;
}
[first_app.html]
<!doctype html>
<html>
<head>
<title>첫 번째 애플리케이션</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
{% from "_formhelpers.html" import render_field %}
<div>이름을 입력해 주세요.</div>
<form method=post action="/hello">
<dl>
{{ render_field(form.sayhello) }}
</dl>
<input type=submit value='이름 입력' name='submit_btn'>
</form>
</body>
</html>
☑️결과 페이지 만들기☑️
<!doctype html>
<html>
<head>
<title>첫 번째 애플리케이션</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<div>{{ name }} 님 안녕하세요!</div>
</body>
</html>
☑️로컬 서버 실행☑️
python app.py