zoukankan      html  css  js  c++  java
  • flask 源码专题(八):路由加载

    1.示例代码

    from flask import Flask
    
    app = Flask(__name__,static_url_path='/xx')
    
    @app.route('/index')
    def index():
        return 'hello world

    2.路由加载源码分析

    2.1先执行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

    2.2 执行add_url_rule函数

    def add_url_rule(
        self,
        rule,
        endpoint=None,
        view_func=None,
        provide_automatic_options=None,
        **options
    ):
        if endpoint is None:
            endpoint = _endpoint_from_view_func(view_func)
            options["endpoint"] = endpoint
            methods = options.pop("methods", None)
    
            if methods is None:
                methods = getattr(view_func, "methods", None) or ("GET",)
    
                rule = self.url_rule_class(rule, methods=methods, **options)
    
                self.url_map.add(rule)
                if view_func is not None:
                    self.view_functions[endpoint] = view_func
    1. 将 url = /index 和 methods = [GET,POST]endpoint = "index"封装到Rule对象
    2. 将Rule对象添加到 app.url_map中。
    3. 把endpoint和函数的对应关系放到 app.view_functions中。
    4. 当一个请求过来时,先拿路由在app.url_map找对应的别名,再在app.view_functions中找到别名对应的视图函数
  • 相关阅读:
    ES6 学习记录
    Windows 服务开发 以及 重启IIS应用池
    IIS部署.net core 3.1踩坑总结
    VS 2019背景全透明以及插件、特效
    深拷贝和浅拷贝的区别
    Vue全家桶以及常用知识点
    C#设计模式
    博客园装扮教程
    Exp5 单元测试
    Exp4 代码评审
  • 原文地址:https://www.cnblogs.com/qiu-hua/p/12637748.html
Copyright © 2011-2022 走看看