[Flask] 메세지 플래싱 (Message Flashing)
Flask 웹어플리케이션에서는 정보 메세지를 쉽게 생성할 수 있다. Flask 프레임워크의 플래싱 기능을 이용하면 하나의 뷰에서 메세지를 생성하고 next 라는 뷰 함수에서 이를 렌더링 할 수 있다.
파일명 : 12_messaage_flashing.py
from flask import Flask, flash, redirect, render_template, request, url_for
app = Flask(__name__)
app.secret_key = 'random string'
@app.route('/')
def index():
return render_template('12_index.html')
@app.route('/login', methods = ['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or \
request.form['password'] != 'admin':
error = 'Invalid username or password. Please try again!'
else:
flash('You were successfully logged in')
return redirect(url_for('index'))
return render_template('12_login.html', error = error)
if __name__ == "__main__":
app.run(debug = True)
username 과 password 가 "admin" 이 아니면 잘못된 계정정보를 입력했다는 문자열을 error 변수에 치환한다. 두 개 모두 "admin" 이면 성공적으로 로그인되었다는 메세지를 플래싱하고 index() 함수를 호출한다. 12_index.html 이 브라우저에 렌더링된다.
파일명 : 12_index.html
<!doctype html>
<html>
<head>
<title>Flask Message flashing</title>
</head>
<body>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<h1>Flask Message Flashing Example</h1>
<p>Do you want to <a href = "{{ url_for('login') }}"><b>log in?</b></a></p>
</body>
</html>
get_flashed_message() 함수를 이용하여 플래싱된 메세지를 가져온다. 메세지가 있으면 그 메세지를 출력하고, 메세지가 없으면 아무 처리도 하지 않는다.
파일명 : 12_login.html
<!doctype html>
<html>
<body>
<h1>Login</h1>
{% if error %}
<p><strong>Error:</strong> {{ error }}
{% endif %}
<form action = "" method = post>
<dl>
<dt>Username:</dt>
<dd>
<input type = text name = username value = "{{request.form.username }}">
</dd>
<dt>Password:</dt>
<dd><input type = password name = password></dd>
</dl>
<p><input type = submit value = Login></p>
</form>
</body>
</html>
12_messaage_flashing.py 에서 error 변수에 저장된 문자열이 있으면 그 문자열을 출력하고 그렇지 않으면 아무 처리도 하지 않는다. 사용자로부터 username 과 password 를 입력받는 페이지이다.