Flask的訊息提示異常處理

2021-07-16 07:58:32 字數 2305 閱讀 7663

一、訊息提示

flask提供訊息閃現機制,方便在應用中訊息提示;

首先匯入flash方法,再對secret_key進行賦值,以對訊息加密;

然後定義乙個路由,使用flash方法,並返回模板;

#-*-coding:utf8-*-

from flask import flask, flash, render_template,request

def hello_user():

flash("welcomt to china")

return render_template("index.html")

def login():

form=request.form

username=form.get('username')

password=form.get('password')

if not username:

flash("please enter username")

return render_template("index.html")

if not password:

flash("please enter password")

return render_template("index.html")

if username=="wencheng" and password=="123":

flash("login succeed")

return render_template("index.html")

else:

flash("username or password is not correcct")

return render_template("index.html")

if __name__ == '__main__':

indexhtml檔案**如下,呈現給使用者的樣式在這裡指定;

例舉幾個樣式:

二、異常處理

對於不存在的檔名部分,預設處理機制顯示如下;

對於使用者來說,是頁面不友好的;

使用裝置器errorhandler捕獲錯誤,然後對指定錯誤進行處理;

#-*-coding:utf8-*-

from flask import flask, flash, render_template,request

def hello_user():

flash("welcomt to china")

return render_template("index.html")

def not_found(e):

return render_template("404.html")

if __name__ == '__main__':

捕獲的404顯示頁面**如下;

顯示效果如下:

三、丟擲異常

有時根據需求,需要主動丟擲異常,則首先匯入abort方法,再使用abort方法丟擲指定異常;

#-*-coding:utf8-*-

from flask import flask, flash, render_template,request, abort

def hello_user():

flash("welcomt to china")

return render_template("index.html")

def not_found(e):

return render_template("404.html")

def users(user_id):

if int(user_id) == 1:

return render_template("user.html")

else:

#主動丟擲異常

abort(404)

if __name__ == '__main__':

Flask第二節 訊息提示 異常處理

1.訊息提示 1.匯入flash模組,書寫路由 訊息提示和加密 123 flash hello jikexueyuan from flask import flask,render template,flash 123 defhello world flash hello jikexueyuan r...

flask異常處理

在view函式中,如果需要中斷request,可以使用abort 500 或者直接raise exception。當然我們還需要返回乙個出錯資訊給前端,所以需要定製一下errorhandler。一般只需要兩個handler即可,乙個是404錯誤,乙個是500一類的伺服器端錯誤。當然也可以自定義錯誤。...

Flask 請求異常處理

在整個請求的過程當中,如果反生錯誤,或者需要根據不同的狀態碼返回對應的錯誤資訊 abort中斷請求from flask import flask defhello world abort 404 請求到此中斷,後面的不會執行,並且這裡的http的狀態碼為401 return hello,world ...