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.

posted @ 2020-11-29 14:07  Mz1  阅读(210)  评论(0编辑  收藏  举报