转载 http://python.jobbole.com/80956/
有原文https://ains.co/blog/things-which-arent-magic-flask-part-1.html
python简单装饰器
# This is our decorator
def simple_decorator(f):
# This is the new function we're going to return
# This function will be used in place of our original definition
def wrapper():
print "Entering Function"
f()
print "Exited Function"
return wrapper
@simple_decorator
def hello():
print "Hello World"
hello()
运行上述代码会输出以下结果:
Entering Function
Hello World
Exited Function
带参数的装饰器
def decorator_factory(enter_message, exit_message):
# We're going to return this decorator
def simple_decorator(f):
def wrapper():
print enter_message
f()
print exit_message
return wrapper
return simple_decorator
@decorator_factory("Start", "End")
def hello():
print "Hello World"
hello()
u结果
Start
Hello World
End
j简单实现Flask 路由
class NotFlask():
def __init__(self):
self.routes = {}
def route(self, route_str):
def decorator(f):
self.routes[route_str] = f
return f
return decorator
def serve(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 = NotFlask()
@app.route("/")
def hello():
return "Hello World!"
print app.serve("/")
u结果
Hello World!