werkzeug源码分析:routing(路由)

werkzeug的routing模块探究

怎么根据请求信息寻找对应的处理函数,这就需要路由功能,routing模块的功能就是提供路由,主要有三个重要的类组成,下面逐个分析:

Rule

Rule类主要用于存储单个路由规则,定义了url和endpoint的映射,同时能指定允许的请求方法。__init__方法主要做这些初始化。

@implements_to_string
class Rule(RuleFactory):

    def __init__(
        self,
        string,
        defaults=None,
        subdomain=None,
        methods=None,
        build_only=False,
        endpoint=None,
        strict_slashes=None,
        redirect_to=None,
        alias=False,
        host=None,
    ):
        if not string.startswith("/"):
            raise ValueError("urls must start with a leading slash")
        self.rule = string
        self.is_leaf = not string.endswith("/")

        self.map = None
        self.strict_slashes = strict_slashes
        self.subdomain = subdomain
        self.host = host
        self.defaults = defaults
        self.build_only = build_only
        self.alias = alias
        if methods is None:
            self.methods = None
        else:
            if isinstance(methods, str):
                raise TypeError("param `methods` should be `Iterable[str]`, not `str`")
            self.methods = set([x.upper() for x in methods])
            if "HEAD" not in self.methods and "GET" in self.methods:
                self.methods.add("HEAD")
        self.endpoint = endpoint
        self.redirect_to = redirect_to

        if defaults:
            self.arguments = set(map(str, defaults))
        else:
            self.arguments = set()
        self._trace = self._converters = self._regex = self._argument_weights = None

Rule通过bind方法和Map进行绑定,绑定之后,路由映射Map就可以获取这条路由规则。通俗说法就是路由注册。

def bind(self, map, rebind=False):
    """Bind the url to a map and create a regular expression based on
    the information from the rule itself and the defaults from the map.

    :internal:
    """
    if self.map is not None and not rebind:
        raise RuntimeError("url rule %r already bound to map %r" % (self, self.map))
    self.map = map
    if self.strict_slashes 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值