routing.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. # Copyright 2015 The Tornado Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  4. # not use this file except in compliance with the License. You may obtain
  5. # a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing permissions and limitations
  13. # under the License.
  14. """Flexible routing implementation.
  15. Tornado routes HTTP requests to appropriate handlers using `Router`
  16. class implementations. The `tornado.web.Application` class is a
  17. `Router` implementation and may be used directly, or the classes in
  18. this module may be used for additional flexibility. The `RuleRouter`
  19. class can match on more criteria than `.Application`, or the `Router`
  20. interface can be subclassed for maximum customization.
  21. `Router` interface extends `~.httputil.HTTPServerConnectionDelegate`
  22. to provide additional routing capabilities. This also means that any
  23. `Router` implementation can be used directly as a ``request_callback``
  24. for `~.httpserver.HTTPServer` constructor.
  25. `Router` subclass must implement a ``find_handler`` method to provide
  26. a suitable `~.httputil.HTTPMessageDelegate` instance to handle the
  27. request:
  28. .. code-block:: python
  29. class CustomRouter(Router):
  30. def find_handler(self, request, **kwargs):
  31. # some routing logic providing a suitable HTTPMessageDelegate instance
  32. return MessageDelegate(request.connection)
  33. class MessageDelegate(HTTPMessageDelegate):
  34. def __init__(self, connection):
  35. self.connection = connection
  36. def finish(self):
  37. self.connection.write_headers(
  38. ResponseStartLine("HTTP/1.1", 200, "OK"),
  39. HTTPHeaders({"Content-Length": "2"}),
  40. b"OK")
  41. self.connection.finish()
  42. router = CustomRouter()
  43. server = HTTPServer(router)
  44. The main responsibility of `Router` implementation is to provide a
  45. mapping from a request to `~.httputil.HTTPMessageDelegate` instance
  46. that will handle this request. In the example above we can see that
  47. routing is possible even without instantiating an `~.web.Application`.
  48. For routing to `~.web.RequestHandler` implementations we need an
  49. `~.web.Application` instance. `~.web.Application.get_handler_delegate`
  50. provides a convenient way to create `~.httputil.HTTPMessageDelegate`
  51. for a given request and `~.web.RequestHandler`.
  52. Here is a simple example of how we can we route to
  53. `~.web.RequestHandler` subclasses by HTTP method:
  54. .. code-block:: python
  55. resources = {}
  56. class GetResource(RequestHandler):
  57. def get(self, path):
  58. if path not in resources:
  59. raise HTTPError(404)
  60. self.finish(resources[path])
  61. class PostResource(RequestHandler):
  62. def post(self, path):
  63. resources[path] = self.request.body
  64. class HTTPMethodRouter(Router):
  65. def __init__(self, app):
  66. self.app = app
  67. def find_handler(self, request, **kwargs):
  68. handler = GetResource if request.method == "GET" else PostResource
  69. return self.app.get_handler_delegate(request, handler, path_args=[request.path])
  70. router = HTTPMethodRouter(Application())
  71. server = HTTPServer(router)
  72. `ReversibleRouter` interface adds the ability to distinguish between
  73. the routes and reverse them to the original urls using route's name
  74. and additional arguments. `~.web.Application` is itself an
  75. implementation of `ReversibleRouter` class.
  76. `RuleRouter` and `ReversibleRuleRouter` are implementations of
  77. `Router` and `ReversibleRouter` interfaces and can be used for
  78. creating rule-based routing configurations.
  79. Rules are instances of `Rule` class. They contain a `Matcher`, which
  80. provides the logic for determining whether the rule is a match for a
  81. particular request and a target, which can be one of the following.
  82. 1) An instance of `~.httputil.HTTPServerConnectionDelegate`:
  83. .. code-block:: python
  84. router = RuleRouter([
  85. Rule(PathMatches("/handler"), ConnectionDelegate()),
  86. # ... more rules
  87. ])
  88. class ConnectionDelegate(HTTPServerConnectionDelegate):
  89. def start_request(self, server_conn, request_conn):
  90. return MessageDelegate(request_conn)
  91. 2) A callable accepting a single argument of `~.httputil.HTTPServerRequest` type:
  92. .. code-block:: python
  93. router = RuleRouter([
  94. Rule(PathMatches("/callable"), request_callable)
  95. ])
  96. def request_callable(request):
  97. request.write(b"HTTP/1.1 200 OK\\r\\nContent-Length: 2\\r\\n\\r\\nOK")
  98. request.finish()
  99. 3) Another `Router` instance:
  100. .. code-block:: python
  101. router = RuleRouter([
  102. Rule(PathMatches("/router.*"), CustomRouter())
  103. ])
  104. Of course a nested `RuleRouter` or a `~.web.Application` is allowed:
  105. .. code-block:: python
  106. router = RuleRouter([
  107. Rule(HostMatches("example.com"), RuleRouter([
  108. Rule(PathMatches("/app1/.*"), Application([(r"/app1/handler", Handler)]))),
  109. ]))
  110. ])
  111. server = HTTPServer(router)
  112. In the example below `RuleRouter` is used to route between applications:
  113. .. code-block:: python
  114. app1 = Application([
  115. (r"/app1/handler", Handler1),
  116. # other handlers ...
  117. ])
  118. app2 = Application([
  119. (r"/app2/handler", Handler2),
  120. # other handlers ...
  121. ])
  122. router = RuleRouter([
  123. Rule(PathMatches("/app1.*"), app1),
  124. Rule(PathMatches("/app2.*"), app2)
  125. ])
  126. server = HTTPServer(router)
  127. For more information on application-level routing see docs for `~.web.Application`.
  128. .. versionadded:: 4.5
  129. """
  130. import re
  131. from functools import partial
  132. from tornado import httputil
  133. from tornado.httpserver import _CallableAdapter
  134. from tornado.escape import url_escape, url_unescape, utf8
  135. from tornado.log import app_log
  136. from tornado.util import basestring_type, import_object, re_unescape, unicode_type
  137. from typing import Any, Union, Optional, Awaitable, List, Dict, Pattern, Tuple, overload
  138. class Router(httputil.HTTPServerConnectionDelegate):
  139. """Abstract router interface."""
  140. def find_handler(
  141. self, request: httputil.HTTPServerRequest, **kwargs: Any
  142. ) -> Optional[httputil.HTTPMessageDelegate]:
  143. """Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate`
  144. that can serve the request.
  145. Routing implementations may pass additional kwargs to extend the routing logic.
  146. :arg httputil.HTTPServerRequest request: current HTTP request.
  147. :arg kwargs: additional keyword arguments passed by routing implementation.
  148. :returns: an instance of `~.httputil.HTTPMessageDelegate` that will be used to
  149. process the request.
  150. """
  151. raise NotImplementedError()
  152. def start_request(
  153. self, server_conn: object, request_conn: httputil.HTTPConnection
  154. ) -> httputil.HTTPMessageDelegate:
  155. return _RoutingDelegate(self, server_conn, request_conn)
  156. class ReversibleRouter(Router):
  157. """Abstract router interface for routers that can handle named routes
  158. and support reversing them to original urls.
  159. """
  160. def reverse_url(self, name: str, *args: Any) -> Optional[str]:
  161. """Returns url string for a given route name and arguments
  162. or ``None`` if no match is found.
  163. :arg str name: route name.
  164. :arg args: url parameters.
  165. :returns: parametrized url string for a given route name (or ``None``).
  166. """
  167. raise NotImplementedError()
  168. class _RoutingDelegate(httputil.HTTPMessageDelegate):
  169. def __init__(
  170. self, router: Router, server_conn: object, request_conn: httputil.HTTPConnection
  171. ) -> None:
  172. self.server_conn = server_conn
  173. self.request_conn = request_conn
  174. self.delegate = None # type: Optional[httputil.HTTPMessageDelegate]
  175. self.router = router # type: Router
  176. def headers_received(
  177. self,
  178. start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],
  179. headers: httputil.HTTPHeaders,
  180. ) -> Optional[Awaitable[None]]:
  181. assert isinstance(start_line, httputil.RequestStartLine)
  182. request = httputil.HTTPServerRequest(
  183. connection=self.request_conn,
  184. server_connection=self.server_conn,
  185. start_line=start_line,
  186. headers=headers,
  187. )
  188. self.delegate = self.router.find_handler(request)
  189. if self.delegate is None:
  190. app_log.debug(
  191. "Delegate for %s %s request not found",
  192. start_line.method,
  193. start_line.path,
  194. )
  195. self.delegate = _DefaultMessageDelegate(self.request_conn)
  196. return self.delegate.headers_received(start_line, headers)
  197. def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]:
  198. assert self.delegate is not None
  199. return self.delegate.data_received(chunk)
  200. def finish(self) -> None:
  201. assert self.delegate is not None
  202. self.delegate.finish()
  203. def on_connection_close(self) -> None:
  204. assert self.delegate is not None
  205. self.delegate.on_connection_close()
  206. class _DefaultMessageDelegate(httputil.HTTPMessageDelegate):
  207. def __init__(self, connection: httputil.HTTPConnection) -> None:
  208. self.connection = connection
  209. def finish(self) -> None:
  210. self.connection.write_headers(
  211. httputil.ResponseStartLine("HTTP/1.1", 404, "Not Found"),
  212. httputil.HTTPHeaders(),
  213. )
  214. self.connection.finish()
  215. # _RuleList can either contain pre-constructed Rules or a sequence of
  216. # arguments to be passed to the Rule constructor.
  217. _RuleList = List[
  218. Union[
  219. "Rule",
  220. List[Any], # Can't do detailed typechecking of lists.
  221. Tuple[Union[str, "Matcher"], Any],
  222. Tuple[Union[str, "Matcher"], Any, Dict[str, Any]],
  223. Tuple[Union[str, "Matcher"], Any, Dict[str, Any], str],
  224. ]
  225. ]
  226. class RuleRouter(Router):
  227. """Rule-based router implementation."""
  228. def __init__(self, rules: _RuleList = None) -> None:
  229. """Constructs a router from an ordered list of rules::
  230. RuleRouter([
  231. Rule(PathMatches("/handler"), Target),
  232. # ... more rules
  233. ])
  234. You can also omit explicit `Rule` constructor and use tuples of arguments::
  235. RuleRouter([
  236. (PathMatches("/handler"), Target),
  237. ])
  238. `PathMatches` is a default matcher, so the example above can be simplified::
  239. RuleRouter([
  240. ("/handler", Target),
  241. ])
  242. In the examples above, ``Target`` can be a nested `Router` instance, an instance of
  243. `~.httputil.HTTPServerConnectionDelegate` or an old-style callable,
  244. accepting a request argument.
  245. :arg rules: a list of `Rule` instances or tuples of `Rule`
  246. constructor arguments.
  247. """
  248. self.rules = [] # type: List[Rule]
  249. if rules:
  250. self.add_rules(rules)
  251. def add_rules(self, rules: _RuleList) -> None:
  252. """Appends new rules to the router.
  253. :arg rules: a list of Rule instances (or tuples of arguments, which are
  254. passed to Rule constructor).
  255. """
  256. for rule in rules:
  257. if isinstance(rule, (tuple, list)):
  258. assert len(rule) in (2, 3, 4)
  259. if isinstance(rule[0], basestring_type):
  260. rule = Rule(PathMatches(rule[0]), *rule[1:])
  261. else:
  262. rule = Rule(*rule)
  263. self.rules.append(self.process_rule(rule))
  264. def process_rule(self, rule: "Rule") -> "Rule":
  265. """Override this method for additional preprocessing of each rule.
  266. :arg Rule rule: a rule to be processed.
  267. :returns: the same or modified Rule instance.
  268. """
  269. return rule
  270. def find_handler(
  271. self, request: httputil.HTTPServerRequest, **kwargs: Any
  272. ) -> Optional[httputil.HTTPMessageDelegate]:
  273. for rule in self.rules:
  274. target_params = rule.matcher.match(request)
  275. if target_params is not None:
  276. if rule.target_kwargs:
  277. target_params["target_kwargs"] = rule.target_kwargs
  278. delegate = self.get_target_delegate(
  279. rule.target, request, **target_params
  280. )
  281. if delegate is not None:
  282. return delegate
  283. return None
  284. def get_target_delegate(
  285. self, target: Any, request: httputil.HTTPServerRequest, **target_params: Any
  286. ) -> Optional[httputil.HTTPMessageDelegate]:
  287. """Returns an instance of `~.httputil.HTTPMessageDelegate` for a
  288. Rule's target. This method is called by `~.find_handler` and can be
  289. extended to provide additional target types.
  290. :arg target: a Rule's target.
  291. :arg httputil.HTTPServerRequest request: current request.
  292. :arg target_params: additional parameters that can be useful
  293. for `~.httputil.HTTPMessageDelegate` creation.
  294. """
  295. if isinstance(target, Router):
  296. return target.find_handler(request, **target_params)
  297. elif isinstance(target, httputil.HTTPServerConnectionDelegate):
  298. assert request.connection is not None
  299. return target.start_request(request.server_connection, request.connection)
  300. elif callable(target):
  301. assert request.connection is not None
  302. return _CallableAdapter(
  303. partial(target, **target_params), request.connection
  304. )
  305. return None
  306. class ReversibleRuleRouter(ReversibleRouter, RuleRouter):
  307. """A rule-based router that implements ``reverse_url`` method.
  308. Each rule added to this router may have a ``name`` attribute that can be
  309. used to reconstruct an original uri. The actual reconstruction takes place
  310. in a rule's matcher (see `Matcher.reverse`).
  311. """
  312. def __init__(self, rules: _RuleList = None) -> None:
  313. self.named_rules = {} # type: Dict[str, Any]
  314. super(ReversibleRuleRouter, self).__init__(rules)
  315. def process_rule(self, rule: "Rule") -> "Rule":
  316. rule = super(ReversibleRuleRouter, self).process_rule(rule)
  317. if rule.name:
  318. if rule.name in self.named_rules:
  319. app_log.warning(
  320. "Multiple handlers named %s; replacing previous value", rule.name
  321. )
  322. self.named_rules[rule.name] = rule
  323. return rule
  324. def reverse_url(self, name: str, *args: Any) -> Optional[str]:
  325. if name in self.named_rules:
  326. return self.named_rules[name].matcher.reverse(*args)
  327. for rule in self.rules:
  328. if isinstance(rule.target, ReversibleRouter):
  329. reversed_url = rule.target.reverse_url(name, *args)
  330. if reversed_url is not None:
  331. return reversed_url
  332. return None
  333. class Rule(object):
  334. """A routing rule."""
  335. def __init__(
  336. self,
  337. matcher: "Matcher",
  338. target: Any,
  339. target_kwargs: Dict[str, Any] = None,
  340. name: str = None,
  341. ) -> None:
  342. """Constructs a Rule instance.
  343. :arg Matcher matcher: a `Matcher` instance used for determining
  344. whether the rule should be considered a match for a specific
  345. request.
  346. :arg target: a Rule's target (typically a ``RequestHandler`` or
  347. `~.httputil.HTTPServerConnectionDelegate` subclass or even a nested `Router`,
  348. depending on routing implementation).
  349. :arg dict target_kwargs: a dict of parameters that can be useful
  350. at the moment of target instantiation (for example, ``status_code``
  351. for a ``RequestHandler`` subclass). They end up in
  352. ``target_params['target_kwargs']`` of `RuleRouter.get_target_delegate`
  353. method.
  354. :arg str name: the name of the rule that can be used to find it
  355. in `ReversibleRouter.reverse_url` implementation.
  356. """
  357. if isinstance(target, str):
  358. # import the Module and instantiate the class
  359. # Must be a fully qualified name (module.ClassName)
  360. target = import_object(target)
  361. self.matcher = matcher # type: Matcher
  362. self.target = target
  363. self.target_kwargs = target_kwargs if target_kwargs else {}
  364. self.name = name
  365. def reverse(self, *args: Any) -> Optional[str]:
  366. return self.matcher.reverse(*args)
  367. def __repr__(self) -> str:
  368. return "%s(%r, %s, kwargs=%r, name=%r)" % (
  369. self.__class__.__name__,
  370. self.matcher,
  371. self.target,
  372. self.target_kwargs,
  373. self.name,
  374. )
  375. class Matcher(object):
  376. """Represents a matcher for request features."""
  377. def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]:
  378. """Matches current instance against the request.
  379. :arg httputil.HTTPServerRequest request: current HTTP request
  380. :returns: a dict of parameters to be passed to the target handler
  381. (for example, ``handler_kwargs``, ``path_args``, ``path_kwargs``
  382. can be passed for proper `~.web.RequestHandler` instantiation).
  383. An empty dict is a valid (and common) return value to indicate a match
  384. when the argument-passing features are not used.
  385. ``None`` must be returned to indicate that there is no match."""
  386. raise NotImplementedError()
  387. def reverse(self, *args: Any) -> Optional[str]:
  388. """Reconstructs full url from matcher instance and additional arguments."""
  389. return None
  390. class AnyMatches(Matcher):
  391. """Matches any request."""
  392. def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]:
  393. return {}
  394. class HostMatches(Matcher):
  395. """Matches requests from hosts specified by ``host_pattern`` regex."""
  396. def __init__(self, host_pattern: Union[str, Pattern]) -> None:
  397. if isinstance(host_pattern, basestring_type):
  398. if not host_pattern.endswith("$"):
  399. host_pattern += "$"
  400. self.host_pattern = re.compile(host_pattern)
  401. else:
  402. self.host_pattern = host_pattern
  403. def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]:
  404. if self.host_pattern.match(request.host_name):
  405. return {}
  406. return None
  407. class DefaultHostMatches(Matcher):
  408. """Matches requests from host that is equal to application's default_host.
  409. Always returns no match if ``X-Real-Ip`` header is present.
  410. """
  411. def __init__(self, application: Any, host_pattern: Pattern) -> None:
  412. self.application = application
  413. self.host_pattern = host_pattern
  414. def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]:
  415. # Look for default host if not behind load balancer (for debugging)
  416. if "X-Real-Ip" not in request.headers:
  417. if self.host_pattern.match(self.application.default_host):
  418. return {}
  419. return None
  420. class PathMatches(Matcher):
  421. """Matches requests with paths specified by ``path_pattern`` regex."""
  422. def __init__(self, path_pattern: Union[str, Pattern]) -> None:
  423. if isinstance(path_pattern, basestring_type):
  424. if not path_pattern.endswith("$"):
  425. path_pattern += "$"
  426. self.regex = re.compile(path_pattern)
  427. else:
  428. self.regex = path_pattern
  429. assert len(self.regex.groupindex) in (0, self.regex.groups), (
  430. "groups in url regexes must either be all named or all "
  431. "positional: %r" % self.regex.pattern
  432. )
  433. self._path, self._group_count = self._find_groups()
  434. def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]:
  435. match = self.regex.match(request.path)
  436. if match is None:
  437. return None
  438. if not self.regex.groups:
  439. return {}
  440. path_args = [] # type: List[bytes]
  441. path_kwargs = {} # type: Dict[str, bytes]
  442. # Pass matched groups to the handler. Since
  443. # match.groups() includes both named and
  444. # unnamed groups, we want to use either groups
  445. # or groupdict but not both.
  446. if self.regex.groupindex:
  447. path_kwargs = dict(
  448. (str(k), _unquote_or_none(v)) for (k, v) in match.groupdict().items()
  449. )
  450. else:
  451. path_args = [_unquote_or_none(s) for s in match.groups()]
  452. return dict(path_args=path_args, path_kwargs=path_kwargs)
  453. def reverse(self, *args: Any) -> Optional[str]:
  454. if self._path is None:
  455. raise ValueError("Cannot reverse url regex " + self.regex.pattern)
  456. assert len(args) == self._group_count, (
  457. "required number of arguments " "not found"
  458. )
  459. if not len(args):
  460. return self._path
  461. converted_args = []
  462. for a in args:
  463. if not isinstance(a, (unicode_type, bytes)):
  464. a = str(a)
  465. converted_args.append(url_escape(utf8(a), plus=False))
  466. return self._path % tuple(converted_args)
  467. def _find_groups(self) -> Tuple[Optional[str], Optional[int]]:
  468. """Returns a tuple (reverse string, group count) for a url.
  469. For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method
  470. would return ('/%s/%s/', 2).
  471. """
  472. pattern = self.regex.pattern
  473. if pattern.startswith("^"):
  474. pattern = pattern[1:]
  475. if pattern.endswith("$"):
  476. pattern = pattern[:-1]
  477. if self.regex.groups != pattern.count("("):
  478. # The pattern is too complicated for our simplistic matching,
  479. # so we can't support reversing it.
  480. return None, None
  481. pieces = []
  482. for fragment in pattern.split("("):
  483. if ")" in fragment:
  484. paren_loc = fragment.index(")")
  485. if paren_loc >= 0:
  486. pieces.append("%s" + fragment[paren_loc + 1 :])
  487. else:
  488. try:
  489. unescaped_fragment = re_unescape(fragment)
  490. except ValueError:
  491. # If we can't unescape part of it, we can't
  492. # reverse this url.
  493. return (None, None)
  494. pieces.append(unescaped_fragment)
  495. return "".join(pieces), self.regex.groups
  496. class URLSpec(Rule):
  497. """Specifies mappings between URLs and handlers.
  498. .. versionchanged: 4.5
  499. `URLSpec` is now a subclass of a `Rule` with `PathMatches` matcher and is preserved for
  500. backwards compatibility.
  501. """
  502. def __init__(
  503. self,
  504. pattern: Union[str, Pattern],
  505. handler: Any,
  506. kwargs: Dict[str, Any] = None,
  507. name: str = None,
  508. ) -> None:
  509. """Parameters:
  510. * ``pattern``: Regular expression to be matched. Any capturing
  511. groups in the regex will be passed in to the handler's
  512. get/post/etc methods as arguments (by keyword if named, by
  513. position if unnamed. Named and unnamed capturing groups
  514. may not be mixed in the same rule).
  515. * ``handler``: `~.web.RequestHandler` subclass to be invoked.
  516. * ``kwargs`` (optional): A dictionary of additional arguments
  517. to be passed to the handler's constructor.
  518. * ``name`` (optional): A name for this handler. Used by
  519. `~.web.Application.reverse_url`.
  520. """
  521. matcher = PathMatches(pattern)
  522. super(URLSpec, self).__init__(matcher, handler, kwargs, name)
  523. self.regex = matcher.regex
  524. self.handler_class = self.target
  525. self.kwargs = kwargs
  526. def __repr__(self) -> str:
  527. return "%s(%r, %s, kwargs=%r, name=%r)" % (
  528. self.__class__.__name__,
  529. self.regex.pattern,
  530. self.handler_class,
  531. self.kwargs,
  532. self.name,
  533. )
  534. @overload
  535. def _unquote_or_none(s: str) -> bytes:
  536. pass
  537. @overload # noqa: F811
  538. def _unquote_or_none(s: None) -> None:
  539. pass
  540. def _unquote_or_none(s: Optional[str]) -> Optional[bytes]: # noqa: F811
  541. """None-safe wrapper around url_unescape to handle unmatched optional
  542. groups correctly.
  543. Note that args are passed as bytes so the handler can decide what
  544. encoding to use.
  545. """
  546. if s is None:
  547. return s
  548. return url_unescape(s, encoding=None, plus=False)