• @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
  • 相关阅读:
    易语言软件加VMProtect壳的正确方法
    ghost系统到硬盘完后,重启进入winxp安装的画面变成了蓝屏
    万象客户端设置服务端ip保存在注册表的位置
    php乱码解决
    远程桌面Default.rdp 中各个参数的含义
    关闭自动检测磁盘
    关于collapsed margin(外边距合并)
    position定位
    grunt-replace和grunt-include-replace问题
    关于动态生成dom绑定事件失效的原因
  • 原文地址:https://www.cnblogs.com/eric_yi/p/8325041.html
Copyright © 2020-2023  润新知