当我们新建一个flask项目时,pycharm通常已经为项目定义了一个基本路由
@app.route('/')
def hello_world():
return 'Hello World!'
此时在浏览器中输入地址http://127.0.0.1:5000
,页面会显示出"Hello World!"的字样
如下图所示
那么此时在flask后台程序中,到底发生了什么事情呢??
在上面的例子中,可以看到对hello_world视图函数被app.route这个有参装假器装饰
来看下app.route这个有参装饰器的内部实现原理
app是Flask主程序的类实例化本项目名得到的一个对象
app = Flask(__name__)
然后调用app对象的route方法来装饰hello_world视图函数
route方法的源码:
def route(self, rule, **options):
def decorator(f):
endpoint = options.pop('endpoint', None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
在用app.route装饰hello_world视图函数的时候,实际上app.route中还可以添加一些参数。
比如指定请求的方法的变量:methods=["GET","POST"]
以及指定视图函数的endpoint,相当于Django中视图函数的别名等
在这里,rule参数相当于hello_world视图函数中的"/"路径,options参数中包含methods和endpoint等
在route装饰器里,返回decorator闭包函数。
在decorator闭包函数中,先从options中获取endpoint的值,endpoint的值默认为None
然后调用self.add_url_rule内部方法处理传递的参数rule,endpoint,f等,在这里self指的是app这个对象
查看app对象中的add_url_rule方法:
@setupmethod
def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
if endpoint is None:
endpoint = _endpoint_from_view_func(view_func)
options['endpoint'] = endpoint
methods = options.pop('methods', None)
# if the methods are not given and the view_func object knows its
# methods we can use that instead. If neither exists, we go with
# a tuple of only `