开始看Flask框架, 然而第一个小例子就被难住了. 程序如下:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
难住我的是@app.route('/')这句, 跟java的注解好像, 百度了一下Python装饰器, 跟AOP(面向方面编程)很像.
简单的对装饰器做个解释, 首先定义装饰器函数, 格式如下:
def decorator(arg):
def _decorator(func):
def __decorator(*args, **kwargs):
print('before function called') #TODO 执行函数前的工作
ret=func(*args,**kwargs); #执行函数,ret是返回值
print('after function returning') #TODO 函数返回后的工作
return ret #返回函数结果
return __decorator
return _decorator
#这是调用函数
@decorator("decorator arg") #这里的"decorator arg"会被赋值到arg参数, 不一定是字符串, 也可以是对象
def hello_world(a,b): #这里的hello_word会被赋值到_decorator的func参数, hello_word函数的参数列表会被赋值给__decorator的参数列表, 在这里是a跟b
return "hello world!"
如果不需要某些参数,在定义装饰器函数时要直接跳过这个参数. 就这个例子来说, 如果decorator装饰器不需要arg参数,那么直接从func开始赋值,如下:
def decorator(func):
def _decorator(*args, **kwargs):
print('before function called') #TODO 执行函数前的工作
ret=func(*args,**kwargs); #执行函数,ret是返回值
print('after function returning') #TODO 函数返回后的工作
return ret #返回函数结果
return _decorator
#这是调用函数
@decorator
def hello_world(a,b): #这里的hello_word会被赋值到_decorator的func参数, hello_word函数的参数列表会被赋值给__decorator的参数列表, 在这里是a跟b
return "hello world!"
route装饰器在此处的作用是, 把用户的URL同指定函数联系起来, 比如说Flask的这个入门例子就是把对网站根目录的访问同hello_world联系起来, 我们略微修改一下这个入门例子,
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/another_url')
def another_url():
return 'this is another url!'
if __name__ == '__main__':
app.run()
我们再访问"http://localhost:5000/another_url"这个网址, 显示出"this is another url!", 说明确实如此.
我大致猜测了一下route装饰器的实现,简单的讲应该如下所示:
dict={}<span style="white-space:pre"> </span>#保存URL跟函数的对应关系
def route(arg):
def _route(func):
dict[arg]=func
然后在我们访问页面的时候,直接调用dict[url]()就可以直接调用URL对应的函数.
当然实际上的实现肯定不会这么简单,但这应该能说明原理.
事实上这里的URL路径并不能进行正则匹配, 这也说明Flask是微框架