flask源码之路由系统本质(二)

flask的路由比较特殊,是基于装饰器来实现的,但是究其本质还是通过一个方法来实现的,什么方法呢,请看下面
我们先写个简单列子:

from flask import Flask

app = Flask(__name__)

'''
1.decorator= app.route('/',methods=['GET','POST'],endpoint='hh')
2.@decorator
'''
@app.route('/',methods=['GET','POST'],endpoint='hh')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    app.__call__()
    app.run()

第一步先执行route()函数,我们点开route()看里面源码有这样一段:

 def route(self, rule, **options):
         #rule = /
         #options = {methods=['GET','POST'],endpoint='hh'}
         def decorator(f):
            endpoint = options.pop('endpoint', None)
            self.add_url_rule(rule, endpoint, f, **options)
            return f
        return decorator

从上面可以看出,route你们就是这样一个,第一步其实就是将一些参数放到了作用域里面相当于是一个闭包,闭包给谁用,其实就是给以后谁执行这个函数就给谁用
第二步就是相当于执行了@decorator,就会立即执行里面的decorator()函数,参数就是hello_world函数,看里面的本质其实就是add_url_rule()这个方法,这个里面包含了url,endpoint,以及函数。

所以添加路由映射的本质其实就是执行add_url_rule()方法
所以:

def login():
    return '登录'
app.add_url_rule('/login','n2',login,methods=['GET','POST'])

这样写也是能用的。

这儿还得注意下里面的endpoint,如果endpoint没传值,是空的的话会怎么样,我们点开add_url_rule看里面有一段这样的源码:

   if endpoint is None:
            endpoint = _endpoint_from_view_func(view_func)

view_func是函数,那这返回的是什么呢,我们再找,点开_endpoint_from_view_func,看源码:

def _endpoint_from_view_func(view_func):
    """Internal helper that returns the default endpoint for a given
    function.  This always is the function name.
    """
    assert view_func is not None, 'expected view func if endpoint ' \
                                  'is not provided.'
    return view_func.__name__

其实返回的就是函数名。所以我们如果endpoint不写的话,默认是函数名。

猜你喜欢

转载自blog.csdn.net/huang_yong_peng/article/details/82497341
今日推荐