Rule-based router implementation.
| 298 | |
| 299 | |
| 300 | class RuleRouter(Router): |
| 301 | """Rule-based router implementation.""" |
| 302 | |
| 303 | def __init__(self, rules: Optional[_RuleList] = None) -> None: |
| 304 | """Constructs a router from an ordered list of rules:: |
| 305 | |
| 306 | RuleRouter([ |
| 307 | Rule(PathMatches("/handler"), Target), |
| 308 | # ... more rules |
| 309 | ]) |
| 310 | |
| 311 | You can also omit explicit `Rule` constructor and use tuples of arguments:: |
| 312 | |
| 313 | RuleRouter([ |
| 314 | (PathMatches("/handler"), Target), |
| 315 | ]) |
| 316 | |
| 317 | `PathMatches` is a default matcher, so the example above can be simplified:: |
| 318 | |
| 319 | RuleRouter([ |
| 320 | ("/handler", Target), |
| 321 | ]) |
| 322 | |
| 323 | In the examples above, ``Target`` can be a nested `Router` instance, an instance of |
| 324 | `~.httputil.HTTPServerConnectionDelegate` or an old-style callable, |
| 325 | accepting a request argument. |
| 326 | |
| 327 | :arg rules: a list of `Rule` instances or tuples of `Rule` |
| 328 | constructor arguments. |
| 329 | """ |
| 330 | self.rules = [] # type: List[Rule] |
| 331 | if rules: |
| 332 | self.add_rules(rules) |
| 333 | |
| 334 | def add_rules(self, rules: _RuleList) -> None: |
| 335 | """Appends new rules to the router. |
| 336 | |
| 337 | :arg rules: a list of Rule instances (or tuples of arguments, which are |
| 338 | passed to Rule constructor). |
| 339 | """ |
| 340 | for rule in rules: |
| 341 | if isinstance(rule, (tuple, list)): |
| 342 | assert len(rule) in (2, 3, 4) |
| 343 | if isinstance(rule[0], basestring_type): |
| 344 | rule = Rule(PathMatches(rule[0]), *rule[1:]) |
| 345 | else: |
| 346 | rule = Rule(*rule) |
| 347 | |
| 348 | self.rules.append(self.process_rule(rule)) |
| 349 | |
| 350 | def process_rule(self, rule: "Rule") -> "Rule": |
| 351 | """Override this method for additional preprocessing of each rule. |
| 352 | |
| 353 | :arg Rule rule: a rule to be processed. |
| 354 | :returns: the same or modified Rule instance. |
| 355 | """ |
| 356 | return rule |
| 357 |