flask-analysis
  • 简介
  • 序
  • 代码目录与详解
    • artwork目录
    • docs目录
    • examples目录
    • tests目录
    • 其他辅助文件
  • 主程序剖析
    • 短短几行 flask到底做了啥
    • 路由系统 为何如此简洁高效
    • 路由匹配探秘
    • 全局对象request解析
    • 全局对象g解析
    • 全局对象current_app解析
    • 全局对象session解析
    • flask特性之signal系统
    • flask特性之blueprint
    • flask特性之methodview
    • flask特性之配置系统
    • flask特性之模板系统
  • flask生态
    • 官方文档
    • 扩展推荐
    • 扩展开发
  • 推荐阅读
  • 贡献名单
Powered by GitBook
On this page

Was this helpful?

  1. 主程序剖析

路由系统 为何如此简洁高效

先来看一下falsk是如何定义路由:

from flask import Flask, escape, request

app = Flask(__name__)

@app.route('/')
def hello():
    name = request.args.get("name", "World")
    return f'Hello, {escape(name)}!'

通过代码可知,app.route是定义路由的装饰器,其源码实现为:

class Flask(_PackageBoundObject):

    @setupmethod
    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",)

        methods = set(item.upper() for item in methods)

        required_methods = set(getattr(view_func, "required_methods", ()))

        methods |= required_methods

        rule = self.url_rule_class(rule, methods=methods, **options)
        rule.provide_automatic_options = provide_automatic_options

        self.url_map.add(rule)
        if view_func is not None:
            old_func = self.view_functions.get(endpoint)
            if old_func is not None and old_func != view_func:
                raise AssertionError(
                    "View function mapping is overwriting an "
                    "existing endpoint function: %s" % endpoint
                )
            self.view_functions[endpoint] = view_func


    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

由代码可知,route函数其实调用add_url_rule函数。基本参数为:rule methods enpoint等; add_url_rule的作用主要构造路由相关逻辑,包含werkzeug的routing模块的Map类和Rule类。 url_map就是Map类的实例化对象,rule是Rule的实例化对象,实例化的同时将rule和endpint的关系绑定,同时将rule对象传递给self.url_map的add函数,同时更新view_functions字典,将enpoint和view_func的对应关系更新进去。

rule[本质是url]和view_func的对应关系由endpoint进行匹配的,此时endpoint如果用户未定义的话,默认是view_func的__name__属性,即view_func的名称;

简单的两个函数,就把整个路由逻辑处理的很完美,这又体现出flask微框架的简单高效。

到此,路由相关的处理逻辑就结束了;

Previous短短几行 flask到底做了啥Next路由匹配探秘

Last updated 5 years ago

Was this helpful?