Flask框架重定向,錯誤顯示,Responses響應(yīng)及Sessions會話操作示例
本文實例講述了Flask框架重定向,錯誤顯示,Responses響應(yīng)及Sessions會話操作。分享給大家供大家參考,具體如下:
重定向和錯誤顯示
將用戶重定向到另一個端點,使用redirect(), 要提前中止錯誤請求,請使用abort()函數(shù)
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
- 如果返回了正確類型的響應(yīng)對象,則直接從視圖返回。
- 如果是字符串,則使用該數(shù)據(jù)和默認參數(shù)創(chuàng)建響應(yīng)對象。
- 如果返回元組,則元組中的項可以提供額外信息。這樣的元組必須是這樣的形式,或者至少有一個項必須在元組中。該值將覆蓋狀態(tài)代碼,可以是其他標頭值的列表或字典。(response, status, headers)或者是(response, headers)
如果要在視圖中獲取生成的響應(yīng)對象,可以使用make_response() 函數(shù)
假設(shè)你有如下視圖:
@app.errorhandler(404)
def not_found(error):
return render_template('error.html'), 404
使用make_response()包含返回表達式,獲取響應(yīng)對象并修改它,然后返回它
@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的基礎(chǔ)上實現(xiàn)的,并以加密方式對cookie進行簽名
要使用sessions,必須要設(shè)置私鑰,以下是簡單示例:
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'))
希望本文所述對大家基于flask框架的Python程序設(shè)計有所幫助。
相關(guān)文章
一文教你如何解決Python開發(fā)總是import出錯的問題
經(jīng)常朋友碰到Python開發(fā)的過程中import包報錯的問題,所以本文將和大家介紹一下可編輯安裝(Editable Install)模式,可以輕松解決import出錯的問題,感興趣的可以了解下2025-05-05
Python多進程multiprocessing、進程池用法實例分析
這篇文章主要介紹了Python多進程multiprocessing、進程池用法,結(jié)合實例形式分析了Python多進程multiprocessing、進程池相關(guān)概念、原理、用法及操作注意事項,需要的朋友可以參考下2020-03-03

