map.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  1. from __future__ import annotations
  2. import typing as t
  3. import warnings
  4. from pprint import pformat
  5. from threading import Lock
  6. from urllib.parse import quote
  7. from urllib.parse import urljoin
  8. from urllib.parse import urlunsplit
  9. from .._internal import _get_environ
  10. from .._internal import _wsgi_decoding_dance
  11. from ..datastructures import ImmutableDict
  12. from ..datastructures import MultiDict
  13. from ..exceptions import BadHost
  14. from ..exceptions import HTTPException
  15. from ..exceptions import MethodNotAllowed
  16. from ..exceptions import NotFound
  17. from ..urls import _urlencode
  18. from ..wsgi import get_host
  19. from .converters import DEFAULT_CONVERTERS
  20. from .exceptions import BuildError
  21. from .exceptions import NoMatch
  22. from .exceptions import RequestAliasRedirect
  23. from .exceptions import RequestPath
  24. from .exceptions import RequestRedirect
  25. from .exceptions import WebsocketMismatch
  26. from .matcher import StateMachineMatcher
  27. from .rules import _simple_rule_re
  28. from .rules import Rule
  29. if t.TYPE_CHECKING:
  30. from _typeshed.wsgi import WSGIApplication
  31. from _typeshed.wsgi import WSGIEnvironment
  32. from .converters import BaseConverter
  33. from .rules import RuleFactory
  34. from ..wrappers.request import Request
  35. class Map:
  36. """The map class stores all the URL rules and some configuration
  37. parameters. Some of the configuration values are only stored on the
  38. `Map` instance since those affect all rules, others are just defaults
  39. and can be overridden for each rule. Note that you have to specify all
  40. arguments besides the `rules` as keyword arguments!
  41. :param rules: sequence of url rules for this map.
  42. :param default_subdomain: The default subdomain for rules without a
  43. subdomain defined.
  44. :param strict_slashes: If a rule ends with a slash but the matched
  45. URL does not, redirect to the URL with a trailing slash.
  46. :param merge_slashes: Merge consecutive slashes when matching or
  47. building URLs. Matches will redirect to the normalized URL.
  48. Slashes in variable parts are not merged.
  49. :param redirect_defaults: This will redirect to the default rule if it
  50. wasn't visited that way. This helps creating
  51. unique URLs.
  52. :param converters: A dict of converters that adds additional converters
  53. to the list of converters. If you redefine one
  54. converter this will override the original one.
  55. :param sort_parameters: If set to `True` the url parameters are sorted.
  56. See `url_encode` for more details.
  57. :param sort_key: The sort key function for `url_encode`.
  58. :param host_matching: if set to `True` it enables the host matching
  59. feature and disables the subdomain one. If
  60. enabled the `host` parameter to rules is used
  61. instead of the `subdomain` one.
  62. .. versionchanged:: 3.0
  63. The ``charset`` and ``encoding_errors`` parameters were removed.
  64. .. versionchanged:: 1.0
  65. If ``url_scheme`` is ``ws`` or ``wss``, only WebSocket rules will match.
  66. .. versionchanged:: 1.0
  67. The ``merge_slashes`` parameter was added.
  68. .. versionchanged:: 0.7
  69. The ``encoding_errors`` and ``host_matching`` parameters were added.
  70. .. versionchanged:: 0.5
  71. The ``sort_parameters`` and ``sort_key`` paramters were added.
  72. """
  73. #: A dict of default converters to be used.
  74. default_converters = ImmutableDict(DEFAULT_CONVERTERS)
  75. #: The type of lock to use when updating.
  76. #:
  77. #: .. versionadded:: 1.0
  78. lock_class = Lock
  79. def __init__(
  80. self,
  81. rules: t.Iterable[RuleFactory] | None = None,
  82. default_subdomain: str = "",
  83. strict_slashes: bool = True,
  84. merge_slashes: bool = True,
  85. redirect_defaults: bool = True,
  86. converters: t.Mapping[str, type[BaseConverter]] | None = None,
  87. sort_parameters: bool = False,
  88. sort_key: t.Callable[[t.Any], t.Any] | None = None,
  89. host_matching: bool = False,
  90. ) -> None:
  91. self._matcher = StateMachineMatcher(merge_slashes)
  92. self._rules_by_endpoint: dict[str, list[Rule]] = {}
  93. self._remap = True
  94. self._remap_lock = self.lock_class()
  95. self.default_subdomain = default_subdomain
  96. self.strict_slashes = strict_slashes
  97. self.merge_slashes = merge_slashes
  98. self.redirect_defaults = redirect_defaults
  99. self.host_matching = host_matching
  100. self.converters = self.default_converters.copy()
  101. if converters:
  102. self.converters.update(converters)
  103. self.sort_parameters = sort_parameters
  104. self.sort_key = sort_key
  105. for rulefactory in rules or ():
  106. self.add(rulefactory)
  107. def is_endpoint_expecting(self, endpoint: str, *arguments: str) -> bool:
  108. """Iterate over all rules and check if the endpoint expects
  109. the arguments provided. This is for example useful if you have
  110. some URLs that expect a language code and others that do not and
  111. you want to wrap the builder a bit so that the current language
  112. code is automatically added if not provided but endpoints expect
  113. it.
  114. :param endpoint: the endpoint to check.
  115. :param arguments: this function accepts one or more arguments
  116. as positional arguments. Each one of them is
  117. checked.
  118. """
  119. self.update()
  120. arguments = set(arguments)
  121. for rule in self._rules_by_endpoint[endpoint]:
  122. if arguments.issubset(rule.arguments):
  123. return True
  124. return False
  125. @property
  126. def _rules(self) -> list[Rule]:
  127. return [rule for rules in self._rules_by_endpoint.values() for rule in rules]
  128. def iter_rules(self, endpoint: str | None = None) -> t.Iterator[Rule]:
  129. """Iterate over all rules or the rules of an endpoint.
  130. :param endpoint: if provided only the rules for that endpoint
  131. are returned.
  132. :return: an iterator
  133. """
  134. self.update()
  135. if endpoint is not None:
  136. return iter(self._rules_by_endpoint[endpoint])
  137. return iter(self._rules)
  138. def add(self, rulefactory: RuleFactory) -> None:
  139. """Add a new rule or factory to the map and bind it. Requires that the
  140. rule is not bound to another map.
  141. :param rulefactory: a :class:`Rule` or :class:`RuleFactory`
  142. """
  143. for rule in rulefactory.get_rules(self):
  144. rule.bind(self)
  145. if not rule.build_only:
  146. self._matcher.add(rule)
  147. self._rules_by_endpoint.setdefault(rule.endpoint, []).append(rule)
  148. self._remap = True
  149. def bind(
  150. self,
  151. server_name: str,
  152. script_name: str | None = None,
  153. subdomain: str | None = None,
  154. url_scheme: str = "http",
  155. default_method: str = "GET",
  156. path_info: str | None = None,
  157. query_args: t.Mapping[str, t.Any] | str | None = None,
  158. ) -> MapAdapter:
  159. """Return a new :class:`MapAdapter` with the details specified to the
  160. call. Note that `script_name` will default to ``'/'`` if not further
  161. specified or `None`. The `server_name` at least is a requirement
  162. because the HTTP RFC requires absolute URLs for redirects and so all
  163. redirect exceptions raised by Werkzeug will contain the full canonical
  164. URL.
  165. If no path_info is passed to :meth:`match` it will use the default path
  166. info passed to bind. While this doesn't really make sense for
  167. manual bind calls, it's useful if you bind a map to a WSGI
  168. environment which already contains the path info.
  169. `subdomain` will default to the `default_subdomain` for this map if
  170. no defined. If there is no `default_subdomain` you cannot use the
  171. subdomain feature.
  172. .. versionchanged:: 1.0
  173. If ``url_scheme`` is ``ws`` or ``wss``, only WebSocket rules
  174. will match.
  175. .. versionchanged:: 0.15
  176. ``path_info`` defaults to ``'/'`` if ``None``.
  177. .. versionchanged:: 0.8
  178. ``query_args`` can be a string.
  179. .. versionchanged:: 0.7
  180. Added ``query_args``.
  181. """
  182. server_name = server_name.lower()
  183. if self.host_matching:
  184. if subdomain is not None:
  185. raise RuntimeError("host matching enabled and a subdomain was provided")
  186. elif subdomain is None:
  187. subdomain = self.default_subdomain
  188. if script_name is None:
  189. script_name = "/"
  190. if path_info is None:
  191. path_info = "/"
  192. # Port isn't part of IDNA, and might push a name over the 63 octet limit.
  193. server_name, port_sep, port = server_name.partition(":")
  194. try:
  195. server_name = server_name.encode("idna").decode("ascii")
  196. except UnicodeError as e:
  197. raise BadHost() from e
  198. return MapAdapter(
  199. self,
  200. f"{server_name}{port_sep}{port}",
  201. script_name,
  202. subdomain,
  203. url_scheme,
  204. path_info,
  205. default_method,
  206. query_args,
  207. )
  208. def bind_to_environ(
  209. self,
  210. environ: WSGIEnvironment | Request,
  211. server_name: str | None = None,
  212. subdomain: str | None = None,
  213. ) -> MapAdapter:
  214. """Like :meth:`bind` but you can pass it an WSGI environment and it
  215. will fetch the information from that dictionary. Note that because of
  216. limitations in the protocol there is no way to get the current
  217. subdomain and real `server_name` from the environment. If you don't
  218. provide it, Werkzeug will use `SERVER_NAME` and `SERVER_PORT` (or
  219. `HTTP_HOST` if provided) as used `server_name` with disabled subdomain
  220. feature.
  221. If `subdomain` is `None` but an environment and a server name is
  222. provided it will calculate the current subdomain automatically.
  223. Example: `server_name` is ``'example.com'`` and the `SERVER_NAME`
  224. in the wsgi `environ` is ``'staging.dev.example.com'`` the calculated
  225. subdomain will be ``'staging.dev'``.
  226. If the object passed as environ has an environ attribute, the value of
  227. this attribute is used instead. This allows you to pass request
  228. objects. Additionally `PATH_INFO` added as a default of the
  229. :class:`MapAdapter` so that you don't have to pass the path info to
  230. the match method.
  231. .. versionchanged:: 1.0.0
  232. If the passed server name specifies port 443, it will match
  233. if the incoming scheme is ``https`` without a port.
  234. .. versionchanged:: 1.0.0
  235. A warning is shown when the passed server name does not
  236. match the incoming WSGI server name.
  237. .. versionchanged:: 0.8
  238. This will no longer raise a ValueError when an unexpected server
  239. name was passed.
  240. .. versionchanged:: 0.5
  241. previously this method accepted a bogus `calculate_subdomain`
  242. parameter that did not have any effect. It was removed because
  243. of that.
  244. :param environ: a WSGI environment.
  245. :param server_name: an optional server name hint (see above).
  246. :param subdomain: optionally the current subdomain (see above).
  247. """
  248. env = _get_environ(environ)
  249. wsgi_server_name = get_host(env).lower()
  250. scheme = env["wsgi.url_scheme"]
  251. upgrade = any(
  252. v.strip() == "upgrade"
  253. for v in env.get("HTTP_CONNECTION", "").lower().split(",")
  254. )
  255. if upgrade and env.get("HTTP_UPGRADE", "").lower() == "websocket":
  256. scheme = "wss" if scheme == "https" else "ws"
  257. if server_name is None:
  258. server_name = wsgi_server_name
  259. else:
  260. server_name = server_name.lower()
  261. # strip standard port to match get_host()
  262. if scheme in {"http", "ws"} and server_name.endswith(":80"):
  263. server_name = server_name[:-3]
  264. elif scheme in {"https", "wss"} and server_name.endswith(":443"):
  265. server_name = server_name[:-4]
  266. if subdomain is None and not self.host_matching:
  267. cur_server_name = wsgi_server_name.split(".")
  268. real_server_name = server_name.split(".")
  269. offset = -len(real_server_name)
  270. if cur_server_name[offset:] != real_server_name:
  271. # This can happen even with valid configs if the server was
  272. # accessed directly by IP address under some situations.
  273. # Instead of raising an exception like in Werkzeug 0.7 or
  274. # earlier we go by an invalid subdomain which will result
  275. # in a 404 error on matching.
  276. warnings.warn(
  277. f"Current server name {wsgi_server_name!r} doesn't match configured"
  278. f" server name {server_name!r}",
  279. stacklevel=2,
  280. )
  281. subdomain = "<invalid>"
  282. else:
  283. subdomain = ".".join(filter(None, cur_server_name[:offset]))
  284. def _get_wsgi_string(name: str) -> str | None:
  285. val = env.get(name)
  286. if val is not None:
  287. return _wsgi_decoding_dance(val)
  288. return None
  289. script_name = _get_wsgi_string("SCRIPT_NAME")
  290. path_info = _get_wsgi_string("PATH_INFO")
  291. query_args = _get_wsgi_string("QUERY_STRING")
  292. return Map.bind(
  293. self,
  294. server_name,
  295. script_name,
  296. subdomain,
  297. scheme,
  298. env["REQUEST_METHOD"],
  299. path_info,
  300. query_args=query_args,
  301. )
  302. def update(self) -> None:
  303. """Called before matching and building to keep the compiled rules
  304. in the correct order after things changed.
  305. """
  306. if not self._remap:
  307. return
  308. with self._remap_lock:
  309. if not self._remap:
  310. return
  311. self._matcher.update()
  312. for rules in self._rules_by_endpoint.values():
  313. rules.sort(key=lambda x: x.build_compare_key())
  314. self._remap = False
  315. def __repr__(self) -> str:
  316. rules = self.iter_rules()
  317. return f"{type(self).__name__}({pformat(list(rules))})"
  318. class MapAdapter:
  319. """Returned by :meth:`Map.bind` or :meth:`Map.bind_to_environ` and does
  320. the URL matching and building based on runtime information.
  321. """
  322. def __init__(
  323. self,
  324. map: Map,
  325. server_name: str,
  326. script_name: str,
  327. subdomain: str | None,
  328. url_scheme: str,
  329. path_info: str,
  330. default_method: str,
  331. query_args: t.Mapping[str, t.Any] | str | None = None,
  332. ):
  333. self.map = map
  334. self.server_name = server_name
  335. if not script_name.endswith("/"):
  336. script_name += "/"
  337. self.script_name = script_name
  338. self.subdomain = subdomain
  339. self.url_scheme = url_scheme
  340. self.path_info = path_info
  341. self.default_method = default_method
  342. self.query_args = query_args
  343. self.websocket = self.url_scheme in {"ws", "wss"}
  344. def dispatch(
  345. self,
  346. view_func: t.Callable[[str, t.Mapping[str, t.Any]], WSGIApplication],
  347. path_info: str | None = None,
  348. method: str | None = None,
  349. catch_http_exceptions: bool = False,
  350. ) -> WSGIApplication:
  351. """Does the complete dispatching process. `view_func` is called with
  352. the endpoint and a dict with the values for the view. It should
  353. look up the view function, call it, and return a response object
  354. or WSGI application. http exceptions are not caught by default
  355. so that applications can display nicer error messages by just
  356. catching them by hand. If you want to stick with the default
  357. error messages you can pass it ``catch_http_exceptions=True`` and
  358. it will catch the http exceptions.
  359. Here a small example for the dispatch usage::
  360. from werkzeug.wrappers import Request, Response
  361. from werkzeug.wsgi import responder
  362. from werkzeug.routing import Map, Rule
  363. def on_index(request):
  364. return Response('Hello from the index')
  365. url_map = Map([Rule('/', endpoint='index')])
  366. views = {'index': on_index}
  367. @responder
  368. def application(environ, start_response):
  369. request = Request(environ)
  370. urls = url_map.bind_to_environ(environ)
  371. return urls.dispatch(lambda e, v: views[e](request, **v),
  372. catch_http_exceptions=True)
  373. Keep in mind that this method might return exception objects, too, so
  374. use :class:`Response.force_type` to get a response object.
  375. :param view_func: a function that is called with the endpoint as
  376. first argument and the value dict as second. Has
  377. to dispatch to the actual view function with this
  378. information. (see above)
  379. :param path_info: the path info to use for matching. Overrides the
  380. path info specified on binding.
  381. :param method: the HTTP method used for matching. Overrides the
  382. method specified on binding.
  383. :param catch_http_exceptions: set to `True` to catch any of the
  384. werkzeug :class:`HTTPException`\\s.
  385. """
  386. try:
  387. try:
  388. endpoint, args = self.match(path_info, method)
  389. except RequestRedirect as e:
  390. return e
  391. return view_func(endpoint, args)
  392. except HTTPException as e:
  393. if catch_http_exceptions:
  394. return e
  395. raise
  396. @t.overload
  397. def match( # type: ignore
  398. self,
  399. path_info: str | None = None,
  400. method: str | None = None,
  401. return_rule: t.Literal[False] = False,
  402. query_args: t.Mapping[str, t.Any] | str | None = None,
  403. websocket: bool | None = None,
  404. ) -> tuple[str, t.Mapping[str, t.Any]]:
  405. ...
  406. @t.overload
  407. def match(
  408. self,
  409. path_info: str | None = None,
  410. method: str | None = None,
  411. return_rule: t.Literal[True] = True,
  412. query_args: t.Mapping[str, t.Any] | str | None = None,
  413. websocket: bool | None = None,
  414. ) -> tuple[Rule, t.Mapping[str, t.Any]]:
  415. ...
  416. def match(
  417. self,
  418. path_info: str | None = None,
  419. method: str | None = None,
  420. return_rule: bool = False,
  421. query_args: t.Mapping[str, t.Any] | str | None = None,
  422. websocket: bool | None = None,
  423. ) -> tuple[str | Rule, t.Mapping[str, t.Any]]:
  424. """The usage is simple: you just pass the match method the current
  425. path info as well as the method (which defaults to `GET`). The
  426. following things can then happen:
  427. - you receive a `NotFound` exception that indicates that no URL is
  428. matching. A `NotFound` exception is also a WSGI application you
  429. can call to get a default page not found page (happens to be the
  430. same object as `werkzeug.exceptions.NotFound`)
  431. - you receive a `MethodNotAllowed` exception that indicates that there
  432. is a match for this URL but not for the current request method.
  433. This is useful for RESTful applications.
  434. - you receive a `RequestRedirect` exception with a `new_url`
  435. attribute. This exception is used to notify you about a request
  436. Werkzeug requests from your WSGI application. This is for example the
  437. case if you request ``/foo`` although the correct URL is ``/foo/``
  438. You can use the `RequestRedirect` instance as response-like object
  439. similar to all other subclasses of `HTTPException`.
  440. - you receive a ``WebsocketMismatch`` exception if the only
  441. match is a WebSocket rule but the bind is an HTTP request, or
  442. if the match is an HTTP rule but the bind is a WebSocket
  443. request.
  444. - you get a tuple in the form ``(endpoint, arguments)`` if there is
  445. a match (unless `return_rule` is True, in which case you get a tuple
  446. in the form ``(rule, arguments)``)
  447. If the path info is not passed to the match method the default path
  448. info of the map is used (defaults to the root URL if not defined
  449. explicitly).
  450. All of the exceptions raised are subclasses of `HTTPException` so they
  451. can be used as WSGI responses. They will all render generic error or
  452. redirect pages.
  453. Here is a small example for matching:
  454. >>> m = Map([
  455. ... Rule('/', endpoint='index'),
  456. ... Rule('/downloads/', endpoint='downloads/index'),
  457. ... Rule('/downloads/<int:id>', endpoint='downloads/show')
  458. ... ])
  459. >>> urls = m.bind("example.com", "/")
  460. >>> urls.match("/", "GET")
  461. ('index', {})
  462. >>> urls.match("/downloads/42")
  463. ('downloads/show', {'id': 42})
  464. And here is what happens on redirect and missing URLs:
  465. >>> urls.match("/downloads")
  466. Traceback (most recent call last):
  467. ...
  468. RequestRedirect: http://example.com/downloads/
  469. >>> urls.match("/missing")
  470. Traceback (most recent call last):
  471. ...
  472. NotFound: 404 Not Found
  473. :param path_info: the path info to use for matching. Overrides the
  474. path info specified on binding.
  475. :param method: the HTTP method used for matching. Overrides the
  476. method specified on binding.
  477. :param return_rule: return the rule that matched instead of just the
  478. endpoint (defaults to `False`).
  479. :param query_args: optional query arguments that are used for
  480. automatic redirects as string or dictionary. It's
  481. currently not possible to use the query arguments
  482. for URL matching.
  483. :param websocket: Match WebSocket instead of HTTP requests. A
  484. websocket request has a ``ws`` or ``wss``
  485. :attr:`url_scheme`. This overrides that detection.
  486. .. versionadded:: 1.0
  487. Added ``websocket``.
  488. .. versionchanged:: 0.8
  489. ``query_args`` can be a string.
  490. .. versionadded:: 0.7
  491. Added ``query_args``.
  492. .. versionadded:: 0.6
  493. Added ``return_rule``.
  494. """
  495. self.map.update()
  496. if path_info is None:
  497. path_info = self.path_info
  498. if query_args is None:
  499. query_args = self.query_args or {}
  500. method = (method or self.default_method).upper()
  501. if websocket is None:
  502. websocket = self.websocket
  503. domain_part = self.server_name
  504. if not self.map.host_matching and self.subdomain is not None:
  505. domain_part = self.subdomain
  506. path_part = f"/{path_info.lstrip('/')}" if path_info else ""
  507. try:
  508. result = self.map._matcher.match(domain_part, path_part, method, websocket)
  509. except RequestPath as e:
  510. # safe = https://url.spec.whatwg.org/#url-path-segment-string
  511. new_path = quote(e.path_info, safe="!$&'()*+,/:;=@")
  512. raise RequestRedirect(
  513. self.make_redirect_url(new_path, query_args)
  514. ) from None
  515. except RequestAliasRedirect as e:
  516. raise RequestRedirect(
  517. self.make_alias_redirect_url(
  518. f"{domain_part}|{path_part}",
  519. e.endpoint,
  520. e.matched_values,
  521. method,
  522. query_args,
  523. )
  524. ) from None
  525. except NoMatch as e:
  526. if e.have_match_for:
  527. raise MethodNotAllowed(valid_methods=list(e.have_match_for)) from None
  528. if e.websocket_mismatch:
  529. raise WebsocketMismatch() from None
  530. raise NotFound() from None
  531. else:
  532. rule, rv = result
  533. if self.map.redirect_defaults:
  534. redirect_url = self.get_default_redirect(rule, method, rv, query_args)
  535. if redirect_url is not None:
  536. raise RequestRedirect(redirect_url)
  537. if rule.redirect_to is not None:
  538. if isinstance(rule.redirect_to, str):
  539. def _handle_match(match: t.Match[str]) -> str:
  540. value = rv[match.group(1)]
  541. return rule._converters[match.group(1)].to_url(value)
  542. redirect_url = _simple_rule_re.sub(_handle_match, rule.redirect_to)
  543. else:
  544. redirect_url = rule.redirect_to(self, **rv)
  545. if self.subdomain:
  546. netloc = f"{self.subdomain}.{self.server_name}"
  547. else:
  548. netloc = self.server_name
  549. raise RequestRedirect(
  550. urljoin(
  551. f"{self.url_scheme or 'http'}://{netloc}{self.script_name}",
  552. redirect_url,
  553. )
  554. )
  555. if return_rule:
  556. return rule, rv
  557. else:
  558. return rule.endpoint, rv
  559. def test(self, path_info: str | None = None, method: str | None = None) -> bool:
  560. """Test if a rule would match. Works like `match` but returns `True`
  561. if the URL matches, or `False` if it does not exist.
  562. :param path_info: the path info to use for matching. Overrides the
  563. path info specified on binding.
  564. :param method: the HTTP method used for matching. Overrides the
  565. method specified on binding.
  566. """
  567. try:
  568. self.match(path_info, method)
  569. except RequestRedirect:
  570. pass
  571. except HTTPException:
  572. return False
  573. return True
  574. def allowed_methods(self, path_info: str | None = None) -> t.Iterable[str]:
  575. """Returns the valid methods that match for a given path.
  576. .. versionadded:: 0.7
  577. """
  578. try:
  579. self.match(path_info, method="--")
  580. except MethodNotAllowed as e:
  581. return e.valid_methods # type: ignore
  582. except HTTPException:
  583. pass
  584. return []
  585. def get_host(self, domain_part: str | None) -> str:
  586. """Figures out the full host name for the given domain part. The
  587. domain part is a subdomain in case host matching is disabled or
  588. a full host name.
  589. """
  590. if self.map.host_matching:
  591. if domain_part is None:
  592. return self.server_name
  593. return domain_part
  594. if domain_part is None:
  595. subdomain = self.subdomain
  596. else:
  597. subdomain = domain_part
  598. if subdomain:
  599. return f"{subdomain}.{self.server_name}"
  600. else:
  601. return self.server_name
  602. def get_default_redirect(
  603. self,
  604. rule: Rule,
  605. method: str,
  606. values: t.MutableMapping[str, t.Any],
  607. query_args: t.Mapping[str, t.Any] | str,
  608. ) -> str | None:
  609. """A helper that returns the URL to redirect to if it finds one.
  610. This is used for default redirecting only.
  611. :internal:
  612. """
  613. assert self.map.redirect_defaults
  614. for r in self.map._rules_by_endpoint[rule.endpoint]:
  615. # every rule that comes after this one, including ourself
  616. # has a lower priority for the defaults. We order the ones
  617. # with the highest priority up for building.
  618. if r is rule:
  619. break
  620. if r.provides_defaults_for(rule) and r.suitable_for(values, method):
  621. values.update(r.defaults) # type: ignore
  622. domain_part, path = r.build(values) # type: ignore
  623. return self.make_redirect_url(path, query_args, domain_part=domain_part)
  624. return None
  625. def encode_query_args(self, query_args: t.Mapping[str, t.Any] | str) -> str:
  626. if not isinstance(query_args, str):
  627. return _urlencode(query_args)
  628. return query_args
  629. def make_redirect_url(
  630. self,
  631. path_info: str,
  632. query_args: t.Mapping[str, t.Any] | str | None = None,
  633. domain_part: str | None = None,
  634. ) -> str:
  635. """Creates a redirect URL.
  636. :internal:
  637. """
  638. if query_args is None:
  639. query_args = self.query_args
  640. if query_args:
  641. query_str = self.encode_query_args(query_args)
  642. else:
  643. query_str = None
  644. scheme = self.url_scheme or "http"
  645. host = self.get_host(domain_part)
  646. path = "/".join((self.script_name.strip("/"), path_info.lstrip("/")))
  647. return urlunsplit((scheme, host, path, query_str, None))
  648. def make_alias_redirect_url(
  649. self,
  650. path: str,
  651. endpoint: str,
  652. values: t.Mapping[str, t.Any],
  653. method: str,
  654. query_args: t.Mapping[str, t.Any] | str,
  655. ) -> str:
  656. """Internally called to make an alias redirect URL."""
  657. url = self.build(
  658. endpoint, values, method, append_unknown=False, force_external=True
  659. )
  660. if query_args:
  661. url += f"?{self.encode_query_args(query_args)}"
  662. assert url != path, "detected invalid alias setting. No canonical URL found"
  663. return url
  664. def _partial_build(
  665. self,
  666. endpoint: str,
  667. values: t.Mapping[str, t.Any],
  668. method: str | None,
  669. append_unknown: bool,
  670. ) -> tuple[str, str, bool] | None:
  671. """Helper for :meth:`build`. Returns subdomain and path for the
  672. rule that accepts this endpoint, values and method.
  673. :internal:
  674. """
  675. # in case the method is none, try with the default method first
  676. if method is None:
  677. rv = self._partial_build(
  678. endpoint, values, self.default_method, append_unknown
  679. )
  680. if rv is not None:
  681. return rv
  682. # Default method did not match or a specific method is passed.
  683. # Check all for first match with matching host. If no matching
  684. # host is found, go with first result.
  685. first_match = None
  686. for rule in self.map._rules_by_endpoint.get(endpoint, ()):
  687. if rule.suitable_for(values, method):
  688. build_rv = rule.build(values, append_unknown)
  689. if build_rv is not None:
  690. rv = (build_rv[0], build_rv[1], rule.websocket)
  691. if self.map.host_matching:
  692. if rv[0] == self.server_name:
  693. return rv
  694. elif first_match is None:
  695. first_match = rv
  696. else:
  697. return rv
  698. return first_match
  699. def build(
  700. self,
  701. endpoint: str,
  702. values: t.Mapping[str, t.Any] | None = None,
  703. method: str | None = None,
  704. force_external: bool = False,
  705. append_unknown: bool = True,
  706. url_scheme: str | None = None,
  707. ) -> str:
  708. """Building URLs works pretty much the other way round. Instead of
  709. `match` you call `build` and pass it the endpoint and a dict of
  710. arguments for the placeholders.
  711. The `build` function also accepts an argument called `force_external`
  712. which, if you set it to `True` will force external URLs. Per default
  713. external URLs (include the server name) will only be used if the
  714. target URL is on a different subdomain.
  715. >>> m = Map([
  716. ... Rule('/', endpoint='index'),
  717. ... Rule('/downloads/', endpoint='downloads/index'),
  718. ... Rule('/downloads/<int:id>', endpoint='downloads/show')
  719. ... ])
  720. >>> urls = m.bind("example.com", "/")
  721. >>> urls.build("index", {})
  722. '/'
  723. >>> urls.build("downloads/show", {'id': 42})
  724. '/downloads/42'
  725. >>> urls.build("downloads/show", {'id': 42}, force_external=True)
  726. 'http://example.com/downloads/42'
  727. Because URLs cannot contain non ASCII data you will always get
  728. bytes back. Non ASCII characters are urlencoded with the
  729. charset defined on the map instance.
  730. Additional values are converted to strings and appended to the URL as
  731. URL querystring parameters:
  732. >>> urls.build("index", {'q': 'My Searchstring'})
  733. '/?q=My+Searchstring'
  734. When processing those additional values, lists are furthermore
  735. interpreted as multiple values (as per
  736. :py:class:`werkzeug.datastructures.MultiDict`):
  737. >>> urls.build("index", {'q': ['a', 'b', 'c']})
  738. '/?q=a&q=b&q=c'
  739. Passing a ``MultiDict`` will also add multiple values:
  740. >>> urls.build("index", MultiDict((('p', 'z'), ('q', 'a'), ('q', 'b'))))
  741. '/?p=z&q=a&q=b'
  742. If a rule does not exist when building a `BuildError` exception is
  743. raised.
  744. The build method accepts an argument called `method` which allows you
  745. to specify the method you want to have an URL built for if you have
  746. different methods for the same endpoint specified.
  747. :param endpoint: the endpoint of the URL to build.
  748. :param values: the values for the URL to build. Unhandled values are
  749. appended to the URL as query parameters.
  750. :param method: the HTTP method for the rule if there are different
  751. URLs for different methods on the same endpoint.
  752. :param force_external: enforce full canonical external URLs. If the URL
  753. scheme is not provided, this will generate
  754. a protocol-relative URL.
  755. :param append_unknown: unknown parameters are appended to the generated
  756. URL as query string argument. Disable this
  757. if you want the builder to ignore those.
  758. :param url_scheme: Scheme to use in place of the bound
  759. :attr:`url_scheme`.
  760. .. versionchanged:: 2.0
  761. Added the ``url_scheme`` parameter.
  762. .. versionadded:: 0.6
  763. Added the ``append_unknown`` parameter.
  764. """
  765. self.map.update()
  766. if values:
  767. if isinstance(values, MultiDict):
  768. values = {
  769. k: (v[0] if len(v) == 1 else v)
  770. for k, v in dict.items(values)
  771. if len(v) != 0
  772. }
  773. else: # plain dict
  774. values = {k: v for k, v in values.items() if v is not None}
  775. else:
  776. values = {}
  777. rv = self._partial_build(endpoint, values, method, append_unknown)
  778. if rv is None:
  779. raise BuildError(endpoint, values, method, self)
  780. domain_part, path, websocket = rv
  781. host = self.get_host(domain_part)
  782. if url_scheme is None:
  783. url_scheme = self.url_scheme
  784. # Always build WebSocket routes with the scheme (browsers
  785. # require full URLs). If bound to a WebSocket, ensure that HTTP
  786. # routes are built with an HTTP scheme.
  787. secure = url_scheme in {"https", "wss"}
  788. if websocket:
  789. force_external = True
  790. url_scheme = "wss" if secure else "ws"
  791. elif url_scheme:
  792. url_scheme = "https" if secure else "http"
  793. # shortcut this.
  794. if not force_external and (
  795. (self.map.host_matching and host == self.server_name)
  796. or (not self.map.host_matching and domain_part == self.subdomain)
  797. ):
  798. return f"{self.script_name.rstrip('/')}/{path.lstrip('/')}"
  799. scheme = f"{url_scheme}:" if url_scheme else ""
  800. return f"{scheme}//{host}{self.script_name[:-1]}/{path.lstrip('/')}"