flask_decorators.py
1 ''' 2 Flask中的特殊裝飾器: 3 (1)@app.before_request 4 請求到達視圖函數之前,進行自定義操作,類似django中間件中的process_request,在app中使用則為全局,在藍圖中使用則針對當前藍圖 5 注意正常狀態下return值必須為None 6 (2)@app.after_request 7 響應返回到達客戶端之前,進行自定義操作,類似jango中間件中的process_response,在app中使用則為全局,在藍圖中使用則針對當前藍圖 8 注意正常狀態下視圖函數必須定義一個形參接收response對象,並通過return response返回 9 (3)@app.errorhandler() 10 錯誤狀態碼捕獲執行函數,裝飾器參數務必是4xx或者5xx的int型錯誤狀態碼 11 (4)@app.template_global() :定義裝飾全局模板可用的函數,直接可在模板中進行渲染使用 12 @app.template_filter(): 定義裝飾全局模板可用的過濾器函數,類似django中的自定義過濾器,直接可在模板中使用 13 兩個特殊裝飾器主要用在模板渲染,詳情使用見falsk學習中的jinjia2學習 14 ''' 15 import os 16 17 from flask import Flask, render_template, session, redirect, request, send_file 18 19 app = Flask(__name__) 20 app.debug = True 21 app.secret_key = 'sdfghjhg1234' 22 23 24 # (1)@app.before_request請求達到視圖函數之前裝飾器函數,正常狀態務必return None 25 @app.before_request 26 def b1(): 27 print('b1') 28 urls = ['/login'] 29 if request.path in urls: 30 return None 31 if session.get('username'): 32 return None 33 else: 34 return redirect('/login') 35 36 37 @app.before_request 38 def b2(): 39 print('b2') 40 return None 41 42 43 # (2)@app.after_request響應到達客戶端之前裝飾器函數,正常狀態被裝飾函數必須定義一個形參來接收response,務必return response 44 @app.after_request 45 def a1(response): 46 print('a1') 47 return response 48 49 50 @app.after_request 51 def a2(response): 52 print('a2') 53 return response 54 55 56 # (3)@app.errorhandler(錯誤狀態碼)錯誤捕獲裝飾器,裝飾其中必須傳入4xx或5xx的錯誤狀態碼,同時在被裝飾函數中定義一個形參來接收錯誤信息error 57 @app.errorhandler(404) 58 def notfond(errormessage): 59 print(errormessage) 60 return send_file(os.path.join(os.path.dirname(__file__), 'static', '1.png')) 61 62 63 # (4)@app.template_global()和@app.template_filter()裝飾器函數直接在模板中可以全局使用 64 65 @app.template_global() 66 def sum1(a, b): 67 return a + b 68 69 70 @app.template_filter() 71 def sum2(a, b, c, d): 72 return a + b + c + d 73 74 75 # (5)@app.route()路由視圖裝飾器,第一個參數為請求路徑,其它關鍵字參數使用相見flask之route路由學習 76 # 可以使用app.add_url_rule(rule, endpoint=None, view_func=None,)進行路由 77 @app.route('/login', methods=['GET', 'POST']) 78 def login(): 79 if request.method == 'GET': 80 print('login_get') 81 return render_template('login.html') 82 elif request.method == 'POST': 83 print('login_post') 84 username = request.form.get('username') 85 pwd = request.form.get('pwd') 86 if username == 'yang' and pwd == '123456': 87 session['username'] = username 88 return redirect('/index') 89 else: 90 return '登錄失敗!!!' 91 92 93 @app.route('/index') 94 def index(): 95 print('index') 96 return render_template('index.html') 97 98 99 @app.route('/data') 100 def data(): 101 print('data') 102 return 'data' 103 104 105 @app.route('/detail') 106 def detail(): 107 print('detail') 108 return 'detail' 109 110 111 if __name__ == '__main__': 112 app.run()
index.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>index</title> 6 </head> 7 <body> 8 index頁面 9 </body> 10 </html>