map.py 36 KB

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