@app.route源码流程分析

@app.route(), 是调用了flask.app.py文件里面的Flask类的route方法,route方法所做的事情和add_url_rule类似,是用来为一个URL注册一个视图函数,但是我们知道route方法是以装饰器的方式使用的

    def route(self, rule, **options):
        """sage::
            @app.route('/')
            def index():
                return 'Hello World'
        :param rule: the URL rule as string
        :param endpoint: the endpoint for the registered URL rule.  Flask
                         itself assumes the name of the view function as
                         endpoint
        :param options: the options to be forwarded to the underlying
                        :class:`~werkzeug.routing.Rule` object.  A change
                        to Werkzeug is handling of method options.  methods
                        is a list of methods this rule should be limited
                        to (``GET``, ``POST`` etc.).  By default a rule
                        just listens for ``GET`` (and implicitly ``HEAD``).
                        Starting with Flask 0.6, ``OPTIONS`` is implicitly
                        added and handled by the standard request handling.
        """
        def decorator(f):
            endpoint = options.pop('endpoint', None)
            self.add_url_rule(rule, endpoint, f, **options)
            return f
        return decorator
源代码

参数解析

  • rule:  一个字符串格式的url规则,如:"/login"
  • endpont: 被注册的url的名字,一般用来反向生成url的时候使用,默认把视图函数的名字作为endpoint,如:endpoint="login"
  • **options: 这个options是跟随:class:`~werkzeug.routing.Rule` object定义的,后面会分析这个对象中的具体参数,但有一个methods参数默认是只监听get方法。

函数体解析

# 根据route的装饰器使用方法,我们可以知道f参数就是视图函数。
def decorator(f):
    # 如果options参数中有endpoint则弹出endpoint,并把值赋值给endpoint变量,如果没有则赋值为None
    endpoint = options.pop('endpoint', None)
    # 调用add_url_rule方法,并把rule,endpont,f,**options传递进来,并执行这个方法,详见add_url_rule方法源码分析
    self.add_url_rule(rule, endpoint, f, **options)
    # 返回了返回f
    return f

 

posted @ 2018-01-21 18:45  eric_yi  阅读(2842)  评论(0编辑  收藏  举报