1. 程式人生 > 實用技巧 >web | flask 修飾器實現原理

web | flask 修飾器實現原理

簡單地說就是傳遞函式地址實現了一個呼叫的過程,具體看程式碼:

 1 class NotFlask():
 2     def __init__(self):
 3         self.routes={}
 4         
 5     def route(self, route_str):
 6         def decorator(f):
 7             self.routes[route_str] = f
 8             print("in decorator")
 9             return f
10         print
("in route") 11 return decorator 12 13 def serve(self, path): 14 view_function = self.routes.get(path) 15 if view_function: 16 return view_function() 17 else: 18 raise ValueError('Route "{}" has not been registered'.format(path)) 19
20 21 app = NotFlask() # 例項化一個物件 22 @app.route("/") # 這裡return了一個函式decorator(f) 23 def hello(): # 這裡執行 decorator(hello) 24 return ("Hello World!") 25 26 # 整個流程相當於 (app.route('/'))(def hello():xxxxx) -->@指向的函式(def的函式) 27 28 print(app.serve('/')) 29 30 ''' 31 in route 32 in decorator
33 Hello World! 34 '''

over.