Windows 10家庭中文版,Python 3.6.4,Flask 1.0.2
abort()函數用於提前退出(Google翻譯abort)一個請求,並用指定的錯誤碼返回。
函數原型如下:
flask.abort(status, *args, **kwargs)
第一個status參數可以是一個狀態碼,比如,404,也可以是一個WSGI應用,必不可少!示例如下:
abort(404) # 404 Not Found
abort(Response('Hello World')) # Response包裝的一個WSGI應用
注意,狀態碼要出現在Flask定義的異常號列表(the list of exceptions)中,否則會引發內部服務器錯誤,比如,傳遞2XX、3XX就不可以的。
異常號列表如下:定義在werkzeug.exceptions.default_exceptions中。
下面是我測試:
1 # flask.abort(status, *args, **kwargs) test 2 @app.route('/abort0') 3 def abort0(): 4 abort(300) 5 6 @app.route('/abort1') 7 def abort1(): 8 abort(400) 9 10 @app.route('/abort2') 11 def abort2(): 12 abort(500) 13 14 @app.route('/abort3') 15 def abort3(): 16 abort('A test of flask.abort()') 17 18 @app.route('/abort4') 19 def abort4(): 20 abort(Response('A test of flask.abort(), Response, ')) 21 22 @app.route('/abort5') 23 def abort5(): 24 abort() 25 26 @app.route('/abort6') 27 def abort6(): 28 cnum = request.args.get('num', '') 29 if cnum == '' or not cnum.isdigit(): 30 abort(404) 31 else: 32 abort(int(cnum))
abort0~4是最初寫的,后來寫了abort5、6。
下面是訪問各個鏈接時頁面及命令行顯示(出錯時)的內容:
/abort0
/abort1
/abort2
/abort3
/abort4
/abort5
/abort6
/abort6?num=100
/abort6?num=505
/abort6?num=431
/abort6?num=tom
測試完畢。對abort()函數的使用更熟悉了,該踩的坑都算踩過了吧。
abort()函數的使用有何好處呢?可以讓開發者在檢測到Web訪問錯誤時,立即將錯誤信息返回。錯誤碼中已對應的錯誤,使用錯誤碼返回即可,否則,返回另外的WSGI應用。
另外,在使用abort()函數前要做日志記錄——錯誤日志!前,很重要!否則,日志是記錄不了的!Quickstart文檔中也有說明。
絮叨:
不過,對於傳遞WSGI應用這個功能還有不清楚的地方,等熟悉了什么是WSGI之后,再找機會記錄。
通過編寫上面的代碼,第一次寫了有條件判斷的代碼,熟悉了字符串怎么轉整數、轉整數前的判斷等。
感覺還有一點東西沒有記錄,是什么呢?對了,如何和定制錯誤頁面搭配使用?比如已經為404定制了錯誤頁面,這時執行abort(Response(...)),這時是返回定義錯誤頁面呢,還是
返回abort里面的WSGI應用?
使用下面的代碼初步進行了測試,測試結果顯示 返回了定制的404頁面:
1 # 1043 2 @app.errorhandler(404) 3 def page_not_found(error): 4 ctx = {} 5 ctx['name'] = 'Benjamin' 6 ctx['yourname'] = 'Alice' 7 return render_template('tmpt1.html', **ctx), 404
頁面、Console及命令行輸出:雖然頁面沒有顯示404錯誤,但是,瀏覽器Console里面顯示了此信息——在響應頭里面。
flask.
abort
(status, *args, **kwargs)