zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    vim 常用命令
    centos 安装mysql
    centos部署ftp
    centos 6.8部署nginx
    ndk学习16: unix domain socket
    ndk学习14: 进程
    ndk学习13: proc
    ndk学习11: linux内存管理
    ndk学习10: linux文件系统
    ndk学习9: 动态使用共享库
  • 原文地址:https://www.cnblogs.com/Mz1-rc/p/14056174.html
Copyright © 2011-2022 走看看