除請(qǐng)求對(duì)象之外,還有一個(gè)session 對(duì)象。它允許你在不
同請(qǐng)求間存儲(chǔ)特定用戶的信息。它是在 Cookies 的基礎(chǔ)上實(shí)現(xiàn)的,并且對(duì)
Cookies 進(jìn)行密鑰簽名。這意味著用戶可以查看你 Cookie 的內(nèi)容,但卻不
能修改它,除非用戶知道簽名的密鑰。
要使用會(huì)話,你需要設(shè)置一個(gè)密鑰。這里介紹會(huì)話如何工作:
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
@app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form action="" method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))
# set the secret key. keep this really secret:
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
更多建議: