Flask框架重定向,錯(cuò)誤顯示,Responses響應(yīng)及Sessions會話操作示例
本文實(shí)例講述了Flask框架重定向,錯(cuò)誤顯示,Responses響應(yīng)及Sessions會話操作。分享給大家供大家參考,具體如下:
重定向和錯(cuò)誤顯示
將用戶重定向到另一個(gè)端點(diǎn),使用redirect(), 要提前中止錯(cuò)誤請求,請使用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()
默認(rèn)情況下,會為每個(gè)錯(cuò)誤代碼顯示黑白錯(cuò)誤頁面,如果要自定義錯(cuò)誤頁面,請使用errorhandler() 裝飾器.
Responses
- 如果返回了正確類型的響應(yīng)對象,則直接從視圖返回。
- 如果是字符串,則使用該數(shù)據(jù)和默認(rèn)參數(shù)創(chuàng)建響應(yīng)對象。
- 如果返回元組,則元組中的項(xiàng)可以提供額外信息。這樣的元組必須是這樣的形式,或者至少有一個(gè)項(xiàng)必須在元組中。該值將覆蓋狀態(tài)代碼,可以是其他標(biāo)頭值的列表或字典。(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()
包含返回表達(dá)式,獲取響應(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ǔ)上實(shí)現(xiàn)的,并以加密方式對cookie進(jìn)行簽名
要使用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è)計(jì)有所幫助。
相關(guān)文章
Python 實(shí)現(xiàn)一行輸入多個(gè)值的方法
下面小編就為大家分享一篇Python 實(shí)現(xiàn)一行輸入多個(gè)值的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04一文教你如何解決Python開發(fā)總是import出錯(cuò)的問題
經(jīng)常朋友碰到Python開發(fā)的過程中import包報(bào)錯(cuò)的問題,所以本文將和大家介紹一下可編輯安裝(Editable Install)模式,可以輕松解決import出錯(cuò)的問題,感興趣的可以了解下2025-05-05Python協(xié)程的2種實(shí)現(xiàn)方式分享
在?Python?中,協(xié)程(Coroutine)是一種輕量級的并發(fā)編程方式,可以通過協(xié)作式多任務(wù)來實(shí)現(xiàn)高效的并發(fā)執(zhí)行。本文主要介紹了Python實(shí)現(xiàn)協(xié)程的2種方式,希望對大家有所幫助2023-04-04Python多進(jìn)程multiprocessing、進(jìn)程池用法實(shí)例分析
這篇文章主要介紹了Python多進(jìn)程multiprocessing、進(jìn)程池用法,結(jié)合實(shí)例形式分析了Python多進(jìn)程multiprocessing、進(jìn)程池相關(guān)概念、原理、用法及操作注意事項(xiàng),需要的朋友可以參考下2020-03-03