通过Flask的@app.route来理解python的装饰器

2020-09-22 16:41:00
六月
来源:
https://www.cnblogs.com/sddai/p/13426277.html
转贴 707

@app.route和装饰器

1、不带参数的装饰器

def simple_decorator(f):
    def wrapper():
        print("func enter")
        f()        
        print("func exit")
    return wrapper
@simple_decorator
def hello():
    print("Hello World!")
hello()

2、带参数的装饰器

def not_very_simply_decorator(enter_msg,exit_msg):
    def simple_decorator(f):
        def wrapper():
            print(enter_msg)            f()            
            print(exit_msg)        
        return wrapper    
    return simple_decorator
@not_very_simply_decorator("func enter","func exit")
def hello():
    print("Hello World")
hello()

模仿Flask我们使用FlaskBother实现同样的功能,我们添加一个 "route" 字典到我们 FlaskBother 对象中

class FlaskBother():
    def route(self,route_str):
        def decorator(f):
            return f
        return decorator

app = FlaskBother()

@app.route('/')
def hello():
return "Hello World"

我们继续完善:

   class FlaskBother():
    def __init__(self):
        self.routes = {}    
    def route(self,route_str):
        def decorator(f):
            self.routes[route_str] = f            
            return f        
         return decorator    
         
    def server(self,path):
        view_function = self.routes.get(path)        
        if view_function:            
            return view_function()        
        else:             
        raise ValueError('Route "{}" has not been registered'.format(path)

我们尝试运行一下:  

app = FlaskBohter() 
@app.route("/") 
def hello():
    return "Hello World" 
print (app.server("/")


参考: https://www.cnblogs.com/sddai/p/13426277.html


发表评论
评论通过审核后显示。