zoukankan      html  css  js  c++  java
  • @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
  • 相关阅读:
    20200601:百万级int数据量的一个array求和。
    20200602:千万级数据量的list找一个数据。
    20200531:假如Redis里面有1亿个key,其中有10w个key是以某个固定的已知的前缀开头的,如何将它们全部找出来?
    20200530:主从数据库不一致如何解决?
    [USACO06DEC]Milk Patterns G
    [HAOI2016]找相同字符
    [AHOI2013]差异
    [SCOI2012]喵星球上的点名
    [APIO2014]回文串
    [TJOI2015]弦论
  • 原文地址:https://www.cnblogs.com/eric_yi/p/8325041.html
Copyright © 2011-2022 走看看