본문 바로가기
PRACTICE/Basic

[Flask] 로그인 페이지, 로그인 성공 시 flash 메시지 출력하기

by 1005 2020. 11. 25.

 

< 폴더 경로 >

 

 

< index.html >

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!doctype html>
<html>
   <head>
      <title>Flask Message flashing</title>
   </head>
   <body>
        {% with messages = get_flashed_messages() %} <!--py를 통해 값을 받아서 html에 출력가능.-->
        {% if messages %}
            <ul>
               {% for mes in messages %}
               <li>{{ mes }}</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>
 

 

< login.html >

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!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>
 

 

< app.py >

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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('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('login.html', error = error)
 
if __name__ == "__main__":
   app.run(host='0.0.0.0', port = 80, debug = True)

 

< 실행 >

 

 

첫화면

 

username은 son, password는 1234로 로그인을 시도할 경우,

 

등록이 되어있지 않아 Error메시지가 뜬다. 

 

 

 

 

 

 

username와 password를 admin으로 작성하고 로그인을 시도할 경우,

로그인이 성공했다는 flash 메시지를 받을 수 있다. 

 

 

댓글