重定向和錯誤顯示
將用戶重定向到另一個端點,使用redirect(), 要提前中止錯誤請求,請使用abort()函數
from flask import abort, redirect, url_for
@app.route('/')
def index():
return redirect(url_for('login'))
@app.route('/login')
def login():
abort(401)
this_is_never_executed()
默認情況下,會爲每個錯誤代碼顯示黑白錯誤頁面,如果要自定義錯誤頁面,請使用errorhandler() 裝飾器.
Responses
- 如果返回了正確類型的響應對象,則直接從視圖返回。
- 如果是字符串,則使用該數據和默認參數創建響應對象。
- 如果返回元組,則元組中的項可以提供額外信息。這樣的元組必須是這樣的形式,或者至少有一個項必須在元組中。該值將覆蓋狀態代碼,可以是其他標頭值的列表或字典。(response, status, headers)或者是(response, headers)
如果要在視圖中獲取生成的響應對象,可以使用make_response() 函數
假設你有如下視圖:
@app.errorhandler(404)
def not_found(error):
return render_template('error.html'), 404
使用make_response()包含返回表達式,獲取響應對象並修改它,然後返回它
@app.errorhandler(404)
def not_found(error):
resp = make_response(render_template('error.html'), 404)
resp.headers['X-Something'] = 'A value'
return resp
Sessions會話追蹤
session在cookie的基礎上實現的,並以加密方式對cookie進行簽名
要使用sessions,必須要設置私鑰,以下是簡單示例:
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
@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 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'))