Flask設置和獲取session案例

from flask import Flask, render_template, request,make_response,session,redirect,url_for
app = Flask(__name__)
app.secret_key = 'any random string'

@app.route('/')
def index():
    if 'username' in session:
        username = session['username']
        return ('Logged in as ' + username + '<br>' +
         "<b><a href = '/logout'>click here to log out</a></b>")
    else:
        return ("You are not logged in <br> <b><a href = '/login'>" + "click here to log in</a></b>")

@app.route('/login', methods = ['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    else:
        return render_template('new6.html')


@app.route('/logout')
def logout():
   # remove the username from the session if it is there
   session.pop('username', None)
   return redirect(url_for('index'))


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

new6.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>12212</title>
</head>
<body>
<form action = "" method = "post">
    <p><input type = text name = username></p>
    <p><input type = submit value = Login></p>
</form>

</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章