본문 바로가기
PRACTICE/Basic

[Flask] Sessions 예제

by 1005 2020. 9. 24.

 

 

Flask – Sessions - Tutorialspoint

Flask – Sessions Like Cookie, Session data is stored on client. Session is the time interval when a client logs into a server and logs out of it. The data, which is needed to be held across this session, is stored in the client browser. A session with ea

www.tutorialspoint.com

 

< 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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from flask import Flask, url_for
from flask import render_template
from flask import request, make_response
from flask import session, redirect, escape
 
app = Flask(__name__)
app.secret_key = 'any random string' #서버상에 동작하는 어플리케이션 구분을 위해서 secret_key 사용함. 
 
@app.route('/')
def index():
    if 'username' in session: #session안에 username이 있으면 로그인 됨.
        username = session['username']
        return 'Logged in as ' + username + '<br>' + \
                "<b><a href = '/logout'> click here to log out</a></b>"
 
    #session안에 username에 없으면 로그인 안됨.
    return "You are not logged in <br><a href = '/login'> click here to log in </a>"
 
@app.route('/login', methods = ['GET''POST']) #브라우저의 기본은 get방식. 처음엔 세션값이 없음. 
def login():
    if request.method == 'POST'#request.method를 통해 get으로 왔는지 post로 왔는지 확인함. 
        session['username'= request.form['username']
        return redirect(url_for('index'))
 
    # 파이썬 코드에서는 주석이지만 브라우저상에서는 주석이 제거되고 
    # 텍스트로 받아지며 html값이 출력됨. 
    return ''
    <form action = "" method = "post">
        <p><input type = "text" name = "username" /></p>
        <p><input type = "submit" value = "Login" /></p>
    </form>
    '''
@app.route('/logout')
def logout():
    # remove the username from the session if it is there
    session.pop('username'None
    # username키에 저장된 value값을 None 해줌. == 세션 지움. 
    # 디폴트값으로 None을 사용하고 value에 값이 있으면 그 값을 반환함. 
    return redirect(url_for('index'))
 
if __name__ == '__main__':
    app.run(host='0.0.0.0', port = 80, debug = True)
 
# 페이지가 바뀌면 세션이 끊김. == 세션값이 바뀌면 세션이 끊김. 
# 따라서 페이지가 바뀔 때 마다 세션을 넘겨줘야함. 
 
 

 

 

 

 

 

댓글