Flask框架重定向,錯誤顯示,Responses響應及Sessions會話操作示例
本文實例講述了Flask框架重定向,錯誤顯示,Responses響應及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
- 如果返回了正確類型的響應對象,則直接從視圖返回。
- 如果是字符串,則使用該數(shù)據(jù)和默認參數(shù)創(chuàng)建響應對象。
- 如果返回元組,則元組中的項可以提供額外信息。這樣的元組必須是這樣的形式,或者至少有一個項必須在元組中。該值將覆蓋狀態(tài)代碼,可以是其他標頭值的列表或字典。(response, status, headers)或者是(response, headers)
如果要在視圖中獲取生成的響應對象,可以使用make_response() 函數(shù)
假設你有如下視圖:
@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的基礎上實現(xiàn)的,并以加密方式對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'))
希望本文所述對大家基于flask框架的Python程序設計有所幫助。
相關文章
Python連接數(shù)據(jù)庫使用matplotlib畫柱形圖
這篇文章主要介紹了Python連接數(shù)據(jù)庫使用matplotlib畫柱形圖,文章通過實例展開對主題的相關介紹。具有一定的知識參考價值性,感興趣的小伙伴可以參考一下2022-06-06PYQT5 vscode聯(lián)合操作qtdesigner的方法
這篇文章主要介紹了PYQT5 vscode聯(lián)合操作qtdesigner的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03Python Selenium 之關閉窗口close與quit的方法
今天小編就為大家分享一篇Python Selenium 之關閉窗口close與quit的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02對python中array.sum(axis=?)的用法介紹
今天小編就為大家分享一篇對python中array.sum(axis=?)的用法介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06