map.py 36 KB

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