routing.py 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332
  1. """When it comes to combining multiple controller or view functions
  2. (however you want to call them) you need a dispatcher. A simple way
  3. would be applying regular expression tests on the ``PATH_INFO`` and
  4. calling registered callback functions that return the value then.
  5. This module implements a much more powerful system than simple regular
  6. expression matching because it can also convert values in the URLs and
  7. build URLs.
  8. Here a simple example that creates a URL map for an application with
  9. two subdomains (www and kb) and some URL rules:
  10. .. code-block:: python
  11. m = Map([
  12. # Static URLs
  13. Rule('/', endpoint='static/index'),
  14. Rule('/about', endpoint='static/about'),
  15. Rule('/help', endpoint='static/help'),
  16. # Knowledge Base
  17. Subdomain('kb', [
  18. Rule('/', endpoint='kb/index'),
  19. Rule('/browse/', endpoint='kb/browse'),
  20. Rule('/browse/<int:id>/', endpoint='kb/browse'),
  21. Rule('/browse/<int:id>/<int:page>', endpoint='kb/browse')
  22. ])
  23. ], default_subdomain='www')
  24. If the application doesn't use subdomains it's perfectly fine to not set
  25. the default subdomain and not use the `Subdomain` rule factory. The
  26. endpoint in the rules can be anything, for example import paths or
  27. unique identifiers. The WSGI application can use those endpoints to get the
  28. handler for that URL. It doesn't have to be a string at all but it's
  29. recommended.
  30. Now it's possible to create a URL adapter for one of the subdomains and
  31. build URLs:
  32. .. code-block:: python
  33. c = m.bind('example.com')
  34. c.build("kb/browse", dict(id=42))
  35. 'http://kb.example.com/browse/42/'
  36. c.build("kb/browse", dict())
  37. 'http://kb.example.com/browse/'
  38. c.build("kb/browse", dict(id=42, page=3))
  39. 'http://kb.example.com/browse/42/3'
  40. c.build("static/about")
  41. '/about'
  42. c.build("static/index", force_external=True)
  43. 'http://www.example.com/'
  44. c = m.bind('example.com', subdomain='kb')
  45. c.build("static/about")
  46. 'http://www.example.com/about'
  47. The first argument to bind is the server name *without* the subdomain.
  48. Per default it will assume that the script is mounted on the root, but
  49. often that's not the case so you can provide the real mount point as
  50. second argument:
  51. .. code-block:: python
  52. c = m.bind('example.com', '/applications/example')
  53. The third argument can be the subdomain, if not given the default
  54. subdomain is used. For more details about binding have a look at the
  55. documentation of the `MapAdapter`.
  56. And here is how you can match URLs:
  57. .. code-block:: python
  58. c = m.bind('example.com')
  59. c.match("/")
  60. ('static/index', {})
  61. c.match("/about")
  62. ('static/about', {})
  63. c = m.bind('example.com', '/', 'kb')
  64. c.match("/")
  65. ('kb/index', {})
  66. c.match("/browse/42/23")
  67. ('kb/browse', {'id': 42, 'page': 23})
  68. If matching fails you get a ``NotFound`` exception, if the rule thinks
  69. it's a good idea to redirect (for example because the URL was defined
  70. to have a slash at the end but the request was missing that slash) it
  71. will raise a ``RequestRedirect`` exception. Both are subclasses of
  72. ``HTTPException`` so you can use those errors as responses in the
  73. application.
  74. If matching succeeded but the URL rule was incompatible to the given
  75. method (for example there were only rules for ``GET`` and ``HEAD`` but
  76. routing tried to match a ``POST`` request) a ``MethodNotAllowed``
  77. exception is raised.
  78. """
  79. import ast
  80. import difflib
  81. import posixpath
  82. import re
  83. import typing
  84. import typing as t
  85. import uuid
  86. import warnings
  87. from pprint import pformat
  88. from string import Template
  89. from threading import Lock
  90. from types import CodeType
  91. from ._internal import _encode_idna
  92. from ._internal import _get_environ
  93. from ._internal import _to_bytes
  94. from ._internal import _to_str
  95. from ._internal import _wsgi_decoding_dance
  96. from .datastructures import ImmutableDict
  97. from .datastructures import MultiDict
  98. from .exceptions import BadHost
  99. from .exceptions import BadRequest
  100. from .exceptions import HTTPException
  101. from .exceptions import MethodNotAllowed
  102. from .exceptions import NotFound
  103. from .urls import _fast_url_quote
  104. from .urls import url_encode
  105. from .urls import url_join
  106. from .urls import url_quote
  107. from .urls import url_unquote
  108. from .utils import cached_property
  109. from .utils import redirect
  110. from .wsgi import get_host
  111. if t.TYPE_CHECKING:
  112. import typing_extensions as te
  113. from _typeshed.wsgi import WSGIApplication
  114. from _typeshed.wsgi import WSGIEnvironment
  115. from .wrappers.request import Request
  116. from .wrappers.response import Response
  117. _rule_re = re.compile(
  118. r"""
  119. (?P<static>[^<]*) # static rule data
  120. <
  121. (?:
  122. (?P<converter>[a-zA-Z_][a-zA-Z0-9_]*) # converter name
  123. (?:\((?P<args>.*?)\))? # converter arguments
  124. \: # variable delimiter
  125. )?
  126. (?P<variable>[a-zA-Z_][a-zA-Z0-9_]*) # variable name
  127. >
  128. """,
  129. re.VERBOSE,
  130. )
  131. _simple_rule_re = re.compile(r"<([^>]+)>")
  132. _converter_args_re = re.compile(
  133. r"""
  134. ((?P<name>\w+)\s*=\s*)?
  135. (?P<value>
  136. True|False|
  137. \d+.\d+|
  138. \d+.|
  139. \d+|
  140. [\w\d_.]+|
  141. [urUR]?(?P<stringval>"[^"]*?"|'[^']*')
  142. )\s*,
  143. """,
  144. re.VERBOSE,
  145. )
  146. _PYTHON_CONSTANTS = {"None": None, "True": True, "False": False}
  147. def _pythonize(value: str) -> t.Union[None, bool, int, float, str]:
  148. if value in _PYTHON_CONSTANTS:
  149. return _PYTHON_CONSTANTS[value]
  150. for convert in int, float:
  151. try:
  152. return convert(value) # type: ignore
  153. except ValueError:
  154. pass
  155. if value[:1] == value[-1:] and value[0] in "\"'":
  156. value = value[1:-1]
  157. return str(value)
  158. def parse_converter_args(argstr: str) -> t.Tuple[t.Tuple, t.Dict[str, t.Any]]:
  159. argstr += ","
  160. args = []
  161. kwargs = {}
  162. for item in _converter_args_re.finditer(argstr):
  163. value = item.group("stringval")
  164. if value is None:
  165. value = item.group("value")
  166. value = _pythonize(value)
  167. if not item.group("name"):
  168. args.append(value)
  169. else:
  170. name = item.group("name")
  171. kwargs[name] = value
  172. return tuple(args), kwargs
  173. def parse_rule(rule: str) -> t.Iterator[t.Tuple[t.Optional[str], t.Optional[str], str]]:
  174. """Parse a rule and return it as generator. Each iteration yields tuples
  175. in the form ``(converter, arguments, variable)``. If the converter is
  176. `None` it's a static url part, otherwise it's a dynamic one.
  177. :internal:
  178. """
  179. pos = 0
  180. end = len(rule)
  181. do_match = _rule_re.match
  182. used_names = set()
  183. while pos < end:
  184. m = do_match(rule, pos)
  185. if m is None:
  186. break
  187. data = m.groupdict()
  188. if data["static"]:
  189. yield None, None, data["static"]
  190. variable = data["variable"]
  191. converter = data["converter"] or "default"
  192. if variable in used_names:
  193. raise ValueError(f"variable name {variable!r} used twice.")
  194. used_names.add(variable)
  195. yield converter, data["args"] or None, variable
  196. pos = m.end()
  197. if pos < end:
  198. remaining = rule[pos:]
  199. if ">" in remaining or "<" in remaining:
  200. raise ValueError(f"malformed url rule: {rule!r}")
  201. yield None, None, remaining
  202. class RoutingException(Exception):
  203. """Special exceptions that require the application to redirect, notifying
  204. about missing urls, etc.
  205. :internal:
  206. """
  207. class RequestRedirect(HTTPException, RoutingException):
  208. """Raise if the map requests a redirect. This is for example the case if
  209. `strict_slashes` are activated and an url that requires a trailing slash.
  210. The attribute `new_url` contains the absolute destination url.
  211. """
  212. code = 308
  213. def __init__(self, new_url: str) -> None:
  214. super().__init__(new_url)
  215. self.new_url = new_url
  216. def get_response(
  217. self,
  218. environ: t.Optional[t.Union["WSGIEnvironment", "Request"]] = None,
  219. scope: t.Optional[dict] = None,
  220. ) -> "Response":
  221. return redirect(self.new_url, self.code)
  222. class RequestPath(RoutingException):
  223. """Internal exception."""
  224. __slots__ = ("path_info",)
  225. def __init__(self, path_info: str) -> None:
  226. super().__init__()
  227. self.path_info = path_info
  228. class RequestAliasRedirect(RoutingException): # noqa: B903
  229. """This rule is an alias and wants to redirect to the canonical URL."""
  230. def __init__(self, matched_values: t.Mapping[str, t.Any]) -> None:
  231. super().__init__()
  232. self.matched_values = matched_values
  233. class BuildError(RoutingException, LookupError):
  234. """Raised if the build system cannot find a URL for an endpoint with the
  235. values provided.
  236. """
  237. def __init__(
  238. self,
  239. endpoint: str,
  240. values: t.Mapping[str, t.Any],
  241. method: t.Optional[str],
  242. adapter: t.Optional["MapAdapter"] = None,
  243. ) -> None:
  244. super().__init__(endpoint, values, method)
  245. self.endpoint = endpoint
  246. self.values = values
  247. self.method = method
  248. self.adapter = adapter
  249. @cached_property
  250. def suggested(self) -> t.Optional["Rule"]:
  251. return self.closest_rule(self.adapter)
  252. def closest_rule(self, adapter: t.Optional["MapAdapter"]) -> t.Optional["Rule"]:
  253. def _score_rule(rule: "Rule") -> float:
  254. return sum(
  255. [
  256. 0.98
  257. * difflib.SequenceMatcher(
  258. None, rule.endpoint, self.endpoint
  259. ).ratio(),
  260. 0.01 * bool(set(self.values or ()).issubset(rule.arguments)),
  261. 0.01 * bool(rule.methods and self.method in rule.methods),
  262. ]
  263. )
  264. if adapter and adapter.map._rules:
  265. return max(adapter.map._rules, key=_score_rule)
  266. return None
  267. def __str__(self) -> str:
  268. message = [f"Could not build url for endpoint {self.endpoint!r}"]
  269. if self.method:
  270. message.append(f" ({self.method!r})")
  271. if self.values:
  272. message.append(f" with values {sorted(self.values)!r}")
  273. message.append(".")
  274. if self.suggested:
  275. if self.endpoint == self.suggested.endpoint:
  276. if (
  277. self.method
  278. and self.suggested.methods is not None
  279. and self.method not in self.suggested.methods
  280. ):
  281. message.append(
  282. " Did you mean to use methods"
  283. f" {sorted(self.suggested.methods)!r}?"
  284. )
  285. missing_values = self.suggested.arguments.union(
  286. set(self.suggested.defaults or ())
  287. ) - set(self.values.keys())
  288. if missing_values:
  289. message.append(
  290. f" Did you forget to specify values {sorted(missing_values)!r}?"
  291. )
  292. else:
  293. message.append(f" Did you mean {self.suggested.endpoint!r} instead?")
  294. return "".join(message)
  295. class WebsocketMismatch(BadRequest):
  296. """The only matched rule is either a WebSocket and the request is
  297. HTTP, or the rule is HTTP and the request is a WebSocket.
  298. """
  299. class ValidationError(ValueError):
  300. """Validation error. If a rule converter raises this exception the rule
  301. does not match the current URL and the next URL is tried.
  302. """
  303. class RuleFactory:
  304. """As soon as you have more complex URL setups it's a good idea to use rule
  305. factories to avoid repetitive tasks. Some of them are builtin, others can
  306. be added by subclassing `RuleFactory` and overriding `get_rules`.
  307. """
  308. def get_rules(self, map: "Map") -> t.Iterable["Rule"]:
  309. """Subclasses of `RuleFactory` have to override this method and return
  310. an iterable of rules."""
  311. raise NotImplementedError()
  312. class Subdomain(RuleFactory):
  313. """All URLs provided by this factory have the subdomain set to a
  314. specific domain. For example if you want to use the subdomain for
  315. the current language this can be a good setup::
  316. url_map = Map([
  317. Rule('/', endpoint='#select_language'),
  318. Subdomain('<string(length=2):lang_code>', [
  319. Rule('/', endpoint='index'),
  320. Rule('/about', endpoint='about'),
  321. Rule('/help', endpoint='help')
  322. ])
  323. ])
  324. All the rules except for the ``'#select_language'`` endpoint will now
  325. listen on a two letter long subdomain that holds the language code
  326. for the current request.
  327. """
  328. def __init__(self, subdomain: str, rules: t.Iterable[RuleFactory]) -> None:
  329. self.subdomain = subdomain
  330. self.rules = rules
  331. def get_rules(self, map: "Map") -> t.Iterator["Rule"]:
  332. for rulefactory in self.rules:
  333. for rule in rulefactory.get_rules(map):
  334. rule = rule.empty()
  335. rule.subdomain = self.subdomain
  336. yield rule
  337. class Submount(RuleFactory):
  338. """Like `Subdomain` but prefixes the URL rule with a given string::
  339. url_map = Map([
  340. Rule('/', endpoint='index'),
  341. Submount('/blog', [
  342. Rule('/', endpoint='blog/index'),
  343. Rule('/entry/<entry_slug>', endpoint='blog/show')
  344. ])
  345. ])
  346. Now the rule ``'blog/show'`` matches ``/blog/entry/<entry_slug>``.
  347. """
  348. def __init__(self, path: str, rules: t.Iterable[RuleFactory]) -> None:
  349. self.path = path.rstrip("/")
  350. self.rules = rules
  351. def get_rules(self, map: "Map") -> t.Iterator["Rule"]:
  352. for rulefactory in self.rules:
  353. for rule in rulefactory.get_rules(map):
  354. rule = rule.empty()
  355. rule.rule = self.path + rule.rule
  356. yield rule
  357. class EndpointPrefix(RuleFactory):
  358. """Prefixes all endpoints (which must be strings for this factory) with
  359. another string. This can be useful for sub applications::
  360. url_map = Map([
  361. Rule('/', endpoint='index'),
  362. EndpointPrefix('blog/', [Submount('/blog', [
  363. Rule('/', endpoint='index'),
  364. Rule('/entry/<entry_slug>', endpoint='show')
  365. ])])
  366. ])
  367. """
  368. def __init__(self, prefix: str, rules: t.Iterable[RuleFactory]) -> None:
  369. self.prefix = prefix
  370. self.rules = rules
  371. def get_rules(self, map: "Map") -> t.Iterator["Rule"]:
  372. for rulefactory in self.rules:
  373. for rule in rulefactory.get_rules(map):
  374. rule = rule.empty()
  375. rule.endpoint = self.prefix + rule.endpoint
  376. yield rule
  377. class RuleTemplate:
  378. """Returns copies of the rules wrapped and expands string templates in
  379. the endpoint, rule, defaults or subdomain sections.
  380. Here a small example for such a rule template::
  381. from werkzeug.routing import Map, Rule, RuleTemplate
  382. resource = RuleTemplate([
  383. Rule('/$name/', endpoint='$name.list'),
  384. Rule('/$name/<int:id>', endpoint='$name.show')
  385. ])
  386. url_map = Map([resource(name='user'), resource(name='page')])
  387. When a rule template is called the keyword arguments are used to
  388. replace the placeholders in all the string parameters.
  389. """
  390. def __init__(self, rules: t.Iterable["Rule"]) -> None:
  391. self.rules = list(rules)
  392. def __call__(self, *args: t.Any, **kwargs: t.Any) -> "RuleTemplateFactory":
  393. return RuleTemplateFactory(self.rules, dict(*args, **kwargs))
  394. class RuleTemplateFactory(RuleFactory):
  395. """A factory that fills in template variables into rules. Used by
  396. `RuleTemplate` internally.
  397. :internal:
  398. """
  399. def __init__(
  400. self, rules: t.Iterable[RuleFactory], context: t.Dict[str, t.Any]
  401. ) -> None:
  402. self.rules = rules
  403. self.context = context
  404. def get_rules(self, map: "Map") -> t.Iterator["Rule"]:
  405. for rulefactory in self.rules:
  406. for rule in rulefactory.get_rules(map):
  407. new_defaults = subdomain = None
  408. if rule.defaults:
  409. new_defaults = {}
  410. for key, value in rule.defaults.items():
  411. if isinstance(value, str):
  412. value = Template(value).substitute(self.context)
  413. new_defaults[key] = value
  414. if rule.subdomain is not None:
  415. subdomain = Template(rule.subdomain).substitute(self.context)
  416. new_endpoint = rule.endpoint
  417. if isinstance(new_endpoint, str):
  418. new_endpoint = Template(new_endpoint).substitute(self.context)
  419. yield Rule(
  420. Template(rule.rule).substitute(self.context),
  421. new_defaults,
  422. subdomain,
  423. rule.methods,
  424. rule.build_only,
  425. new_endpoint,
  426. rule.strict_slashes,
  427. )
  428. def _prefix_names(src: str) -> ast.stmt:
  429. """ast parse and prefix names with `.` to avoid collision with user vars"""
  430. tree = ast.parse(src).body[0]
  431. if isinstance(tree, ast.Expr):
  432. tree = tree.value # type: ignore
  433. for node in ast.walk(tree):
  434. if isinstance(node, ast.Name):
  435. node.id = f".{node.id}"
  436. return tree
  437. _CALL_CONVERTER_CODE_FMT = "self._converters[{elem!r}].to_url()"
  438. _IF_KWARGS_URL_ENCODE_CODE = """\
  439. if kwargs:
  440. params = self._encode_query_vars(kwargs)
  441. q = "?" if params else ""
  442. else:
  443. q = params = ""
  444. """
  445. _IF_KWARGS_URL_ENCODE_AST = _prefix_names(_IF_KWARGS_URL_ENCODE_CODE)
  446. _URL_ENCODE_AST_NAMES = (_prefix_names("q"), _prefix_names("params"))
  447. class Rule(RuleFactory):
  448. """A Rule represents one URL pattern. There are some options for `Rule`
  449. that change the way it behaves and are passed to the `Rule` constructor.
  450. Note that besides the rule-string all arguments *must* be keyword arguments
  451. in order to not break the application on Werkzeug upgrades.
  452. `string`
  453. Rule strings basically are just normal URL paths with placeholders in
  454. the format ``<converter(arguments):name>`` where the converter and the
  455. arguments are optional. If no converter is defined the `default`
  456. converter is used which means `string` in the normal configuration.
  457. URL rules that end with a slash are branch URLs, others are leaves.
  458. If you have `strict_slashes` enabled (which is the default), all
  459. branch URLs that are matched without a trailing slash will trigger a
  460. redirect to the same URL with the missing slash appended.
  461. The converters are defined on the `Map`.
  462. `endpoint`
  463. The endpoint for this rule. This can be anything. A reference to a
  464. function, a string, a number etc. The preferred way is using a string
  465. because the endpoint is used for URL generation.
  466. `defaults`
  467. An optional dict with defaults for other rules with the same endpoint.
  468. This is a bit tricky but useful if you want to have unique URLs::
  469. url_map = Map([
  470. Rule('/all/', defaults={'page': 1}, endpoint='all_entries'),
  471. Rule('/all/page/<int:page>', endpoint='all_entries')
  472. ])
  473. If a user now visits ``http://example.com/all/page/1`` they will be
  474. redirected to ``http://example.com/all/``. If `redirect_defaults` is
  475. disabled on the `Map` instance this will only affect the URL
  476. generation.
  477. `subdomain`
  478. The subdomain rule string for this rule. If not specified the rule
  479. only matches for the `default_subdomain` of the map. If the map is
  480. not bound to a subdomain this feature is disabled.
  481. Can be useful if you want to have user profiles on different subdomains
  482. and all subdomains are forwarded to your application::
  483. url_map = Map([
  484. Rule('/', subdomain='<username>', endpoint='user/homepage'),
  485. Rule('/stats', subdomain='<username>', endpoint='user/stats')
  486. ])
  487. `methods`
  488. A sequence of http methods this rule applies to. If not specified, all
  489. methods are allowed. For example this can be useful if you want different
  490. endpoints for `POST` and `GET`. If methods are defined and the path
  491. matches but the method matched against is not in this list or in the
  492. list of another rule for that path the error raised is of the type
  493. `MethodNotAllowed` rather than `NotFound`. If `GET` is present in the
  494. list of methods and `HEAD` is not, `HEAD` is added automatically.
  495. `strict_slashes`
  496. Override the `Map` setting for `strict_slashes` only for this rule. If
  497. not specified the `Map` setting is used.
  498. `merge_slashes`
  499. Override :attr:`Map.merge_slashes` for this rule.
  500. `build_only`
  501. Set this to True and the rule will never match but will create a URL
  502. that can be build. This is useful if you have resources on a subdomain
  503. or folder that are not handled by the WSGI application (like static data)
  504. `redirect_to`
  505. If given this must be either a string or callable. In case of a
  506. callable it's called with the url adapter that triggered the match and
  507. the values of the URL as keyword arguments and has to return the target
  508. for the redirect, otherwise it has to be a string with placeholders in
  509. rule syntax::
  510. def foo_with_slug(adapter, id):
  511. # ask the database for the slug for the old id. this of
  512. # course has nothing to do with werkzeug.
  513. return f'foo/{Foo.get_slug_for_id(id)}'
  514. url_map = Map([
  515. Rule('/foo/<slug>', endpoint='foo'),
  516. Rule('/some/old/url/<slug>', redirect_to='foo/<slug>'),
  517. Rule('/other/old/url/<int:id>', redirect_to=foo_with_slug)
  518. ])
  519. When the rule is matched the routing system will raise a
  520. `RequestRedirect` exception with the target for the redirect.
  521. Keep in mind that the URL will be joined against the URL root of the
  522. script so don't use a leading slash on the target URL unless you
  523. really mean root of that domain.
  524. `alias`
  525. If enabled this rule serves as an alias for another rule with the same
  526. endpoint and arguments.
  527. `host`
  528. If provided and the URL map has host matching enabled this can be
  529. used to provide a match rule for the whole host. This also means
  530. that the subdomain feature is disabled.
  531. `websocket`
  532. If ``True``, this rule is only matches for WebSocket (``ws://``,
  533. ``wss://``) requests. By default, rules will only match for HTTP
  534. requests.
  535. .. versionchanged:: 2.1
  536. Percent-encoded newlines (``%0a``), which are decoded by WSGI
  537. servers, are considered when routing instead of terminating the
  538. match early.
  539. .. versionadded:: 1.0
  540. Added ``websocket``.
  541. .. versionadded:: 1.0
  542. Added ``merge_slashes``.
  543. .. versionadded:: 0.7
  544. Added ``alias`` and ``host``.
  545. .. versionchanged:: 0.6.1
  546. ``HEAD`` is added to ``methods`` if ``GET`` is present.
  547. """
  548. def __init__(
  549. self,
  550. string: str,
  551. defaults: t.Optional[t.Mapping[str, t.Any]] = None,
  552. subdomain: t.Optional[str] = None,
  553. methods: t.Optional[t.Iterable[str]] = None,
  554. build_only: bool = False,
  555. endpoint: t.Optional[str] = None,
  556. strict_slashes: t.Optional[bool] = None,
  557. merge_slashes: t.Optional[bool] = None,
  558. redirect_to: t.Optional[t.Union[str, t.Callable[..., str]]] = None,
  559. alias: bool = False,
  560. host: t.Optional[str] = None,
  561. websocket: bool = False,
  562. ) -> None:
  563. if not string.startswith("/"):
  564. raise ValueError("urls must start with a leading slash")
  565. self.rule = string
  566. self.is_leaf = not string.endswith("/")
  567. self.map: "Map" = None # type: ignore
  568. self.strict_slashes = strict_slashes
  569. self.merge_slashes = merge_slashes
  570. self.subdomain = subdomain
  571. self.host = host
  572. self.defaults = defaults
  573. self.build_only = build_only
  574. self.alias = alias
  575. self.websocket = websocket
  576. if methods is not None:
  577. if isinstance(methods, str):
  578. raise TypeError("'methods' should be a list of strings.")
  579. methods = {x.upper() for x in methods}
  580. if "HEAD" not in methods and "GET" in methods:
  581. methods.add("HEAD")
  582. if websocket and methods - {"GET", "HEAD", "OPTIONS"}:
  583. raise ValueError(
  584. "WebSocket rules can only use 'GET', 'HEAD', and 'OPTIONS' methods."
  585. )
  586. self.methods = methods
  587. self.endpoint: str = endpoint # type: ignore
  588. self.redirect_to = redirect_to
  589. if defaults:
  590. self.arguments = set(map(str, defaults))
  591. else:
  592. self.arguments = set()
  593. self._trace: t.List[t.Tuple[bool, str]] = []
  594. def empty(self) -> "Rule":
  595. """
  596. Return an unbound copy of this rule.
  597. This can be useful if want to reuse an already bound URL for another
  598. map. See ``get_empty_kwargs`` to override what keyword arguments are
  599. provided to the new copy.
  600. """
  601. return type(self)(self.rule, **self.get_empty_kwargs())
  602. def get_empty_kwargs(self) -> t.Mapping[str, t.Any]:
  603. """
  604. Provides kwargs for instantiating empty copy with empty()
  605. Use this method to provide custom keyword arguments to the subclass of
  606. ``Rule`` when calling ``some_rule.empty()``. Helpful when the subclass
  607. has custom keyword arguments that are needed at instantiation.
  608. Must return a ``dict`` that will be provided as kwargs to the new
  609. instance of ``Rule``, following the initial ``self.rule`` value which
  610. is always provided as the first, required positional argument.
  611. """
  612. defaults = None
  613. if self.defaults:
  614. defaults = dict(self.defaults)
  615. return dict(
  616. defaults=defaults,
  617. subdomain=self.subdomain,
  618. methods=self.methods,
  619. build_only=self.build_only,
  620. endpoint=self.endpoint,
  621. strict_slashes=self.strict_slashes,
  622. redirect_to=self.redirect_to,
  623. alias=self.alias,
  624. host=self.host,
  625. )
  626. def get_rules(self, map: "Map") -> t.Iterator["Rule"]:
  627. yield self
  628. def refresh(self) -> None:
  629. """Rebinds and refreshes the URL. Call this if you modified the
  630. rule in place.
  631. :internal:
  632. """
  633. self.bind(self.map, rebind=True)
  634. def bind(self, map: "Map", rebind: bool = False) -> None:
  635. """Bind the url to a map and create a regular expression based on
  636. the information from the rule itself and the defaults from the map.
  637. :internal:
  638. """
  639. if self.map is not None and not rebind:
  640. raise RuntimeError(f"url rule {self!r} already bound to map {self.map!r}")
  641. self.map = map
  642. if self.strict_slashes is None:
  643. self.strict_slashes = map.strict_slashes
  644. if self.merge_slashes is None:
  645. self.merge_slashes = map.merge_slashes
  646. if self.subdomain is None:
  647. self.subdomain = map.default_subdomain
  648. self.compile()
  649. def get_converter(
  650. self,
  651. variable_name: str,
  652. converter_name: str,
  653. args: t.Tuple,
  654. kwargs: t.Mapping[str, t.Any],
  655. ) -> "BaseConverter":
  656. """Looks up the converter for the given parameter.
  657. .. versionadded:: 0.9
  658. """
  659. if converter_name not in self.map.converters:
  660. raise LookupError(f"the converter {converter_name!r} does not exist")
  661. return self.map.converters[converter_name](self.map, *args, **kwargs)
  662. def _encode_query_vars(self, query_vars: t.Mapping[str, t.Any]) -> str:
  663. return url_encode(
  664. query_vars,
  665. charset=self.map.charset,
  666. sort=self.map.sort_parameters,
  667. key=self.map.sort_key,
  668. )
  669. def compile(self) -> None:
  670. """Compiles the regular expression and stores it."""
  671. assert self.map is not None, "rule not bound"
  672. if self.map.host_matching:
  673. domain_rule = self.host or ""
  674. else:
  675. domain_rule = self.subdomain or ""
  676. self._trace = []
  677. self._converters: t.Dict[str, "BaseConverter"] = {}
  678. self._static_weights: t.List[t.Tuple[int, int]] = []
  679. self._argument_weights: t.List[int] = []
  680. regex_parts = []
  681. def _build_regex(rule: str) -> None:
  682. index = 0
  683. for converter, arguments, variable in parse_rule(rule):
  684. if converter is None:
  685. for match in re.finditer(r"/+|[^/]+", variable):
  686. part = match.group(0)
  687. if part.startswith("/"):
  688. if self.merge_slashes:
  689. regex_parts.append(r"/+?")
  690. self._trace.append((False, "/"))
  691. else:
  692. regex_parts.append(part)
  693. self._trace.append((False, part))
  694. continue
  695. self._trace.append((False, part))
  696. regex_parts.append(re.escape(part))
  697. if part:
  698. self._static_weights.append((index, -len(part)))
  699. else:
  700. if arguments:
  701. c_args, c_kwargs = parse_converter_args(arguments)
  702. else:
  703. c_args = ()
  704. c_kwargs = {}
  705. convobj = self.get_converter(variable, converter, c_args, c_kwargs)
  706. regex_parts.append(f"(?P<{variable}>{convobj.regex})")
  707. self._converters[variable] = convobj
  708. self._trace.append((True, variable))
  709. self._argument_weights.append(convobj.weight)
  710. self.arguments.add(str(variable))
  711. index = index + 1
  712. _build_regex(domain_rule)
  713. regex_parts.append("\\|")
  714. self._trace.append((False, "|"))
  715. _build_regex(self.rule if self.is_leaf else self.rule.rstrip("/"))
  716. if not self.is_leaf:
  717. self._trace.append((False, "/"))
  718. self._build: t.Callable[..., t.Tuple[str, str]]
  719. self._build = self._compile_builder(False).__get__(self, None)
  720. self._build_unknown: t.Callable[..., t.Tuple[str, str]]
  721. self._build_unknown = self._compile_builder(True).__get__(self, None)
  722. if self.build_only:
  723. return
  724. if not (self.is_leaf and self.strict_slashes):
  725. reps = "*" if self.merge_slashes else "?"
  726. tail = f"(?<!/)(?P<__suffix__>/{reps})"
  727. else:
  728. tail = ""
  729. # Use \Z instead of $ to avoid matching before a %0a decoded to
  730. # a \n by WSGI.
  731. regex = rf"^{''.join(regex_parts)}{tail}$\Z"
  732. self._regex = re.compile(regex)
  733. def match(
  734. self, path: str, method: t.Optional[str] = None
  735. ) -> t.Optional[t.MutableMapping[str, t.Any]]:
  736. """Check if the rule matches a given path. Path is a string in the
  737. form ``"subdomain|/path"`` and is assembled by the map. If
  738. the map is doing host matching the subdomain part will be the host
  739. instead.
  740. If the rule matches a dict with the converted values is returned,
  741. otherwise the return value is `None`.
  742. :internal:
  743. """
  744. if not self.build_only:
  745. require_redirect = False
  746. m = self._regex.search(path)
  747. if m is not None:
  748. groups = m.groupdict()
  749. # we have a folder like part of the url without a trailing
  750. # slash and strict slashes enabled. raise an exception that
  751. # tells the map to redirect to the same url but with a
  752. # trailing slash
  753. if (
  754. self.strict_slashes
  755. and not self.is_leaf
  756. and not groups.pop("__suffix__")
  757. and (
  758. method is None or self.methods is None or method in self.methods
  759. )
  760. ):
  761. path += "/"
  762. require_redirect = True
  763. # if we are not in strict slashes mode we have to remove
  764. # a __suffix__
  765. elif not self.strict_slashes:
  766. del groups["__suffix__"]
  767. result = {}
  768. for name, value in groups.items():
  769. try:
  770. value = self._converters[name].to_python(value)
  771. except ValidationError:
  772. return None
  773. result[str(name)] = value
  774. if self.defaults:
  775. result.update(self.defaults)
  776. if self.merge_slashes:
  777. new_path = "|".join(self.build(result, False)) # type: ignore
  778. if path.endswith("/") and not new_path.endswith("/"):
  779. new_path += "/"
  780. if new_path.count("/") < path.count("/"):
  781. # The URL will be encoded when MapAdapter.match
  782. # handles the RequestPath raised below. Decode
  783. # the URL here to avoid a double encoding.
  784. path = url_unquote(new_path)
  785. require_redirect = True
  786. if require_redirect:
  787. path = path.split("|", 1)[1]
  788. raise RequestPath(path)
  789. if self.alias and self.map.redirect_defaults:
  790. raise RequestAliasRedirect(result)
  791. return result
  792. return None
  793. @staticmethod
  794. def _get_func_code(code: CodeType, name: str) -> t.Callable[..., t.Tuple[str, str]]:
  795. globs: t.Dict[str, t.Any] = {}
  796. locs: t.Dict[str, t.Any] = {}
  797. exec(code, globs, locs)
  798. return locs[name] # type: ignore
  799. def _compile_builder(
  800. self, append_unknown: bool = True
  801. ) -> t.Callable[..., t.Tuple[str, str]]:
  802. defaults = self.defaults or {}
  803. dom_ops: t.List[t.Tuple[bool, str]] = []
  804. url_ops: t.List[t.Tuple[bool, str]] = []
  805. opl = dom_ops
  806. for is_dynamic, data in self._trace:
  807. if data == "|" and opl is dom_ops:
  808. opl = url_ops
  809. continue
  810. # this seems like a silly case to ever come up but:
  811. # if a default is given for a value that appears in the rule,
  812. # resolve it to a constant ahead of time
  813. if is_dynamic and data in defaults:
  814. data = self._converters[data].to_url(defaults[data])
  815. opl.append((False, data))
  816. elif not is_dynamic:
  817. opl.append(
  818. (False, url_quote(_to_bytes(data, self.map.charset), safe="/:|+"))
  819. )
  820. else:
  821. opl.append((True, data))
  822. def _convert(elem: str) -> ast.stmt:
  823. ret = _prefix_names(_CALL_CONVERTER_CODE_FMT.format(elem=elem))
  824. ret.args = [ast.Name(str(elem), ast.Load())] # type: ignore # str for py2
  825. return ret
  826. def _parts(ops: t.List[t.Tuple[bool, str]]) -> t.List[ast.AST]:
  827. parts = [
  828. _convert(elem) if is_dynamic else ast.Str(s=elem)
  829. for is_dynamic, elem in ops
  830. ]
  831. parts = parts or [ast.Str("")]
  832. # constant fold
  833. ret = [parts[0]]
  834. for p in parts[1:]:
  835. if isinstance(p, ast.Str) and isinstance(ret[-1], ast.Str):
  836. ret[-1] = ast.Str(ret[-1].s + p.s)
  837. else:
  838. ret.append(p)
  839. return ret
  840. dom_parts = _parts(dom_ops)
  841. url_parts = _parts(url_ops)
  842. if not append_unknown:
  843. body = []
  844. else:
  845. body = [_IF_KWARGS_URL_ENCODE_AST]
  846. url_parts.extend(_URL_ENCODE_AST_NAMES)
  847. def _join(parts: t.List[ast.AST]) -> ast.AST:
  848. if len(parts) == 1: # shortcut
  849. return parts[0]
  850. return ast.JoinedStr(parts)
  851. body.append(
  852. ast.Return(ast.Tuple([_join(dom_parts), _join(url_parts)], ast.Load()))
  853. )
  854. pargs = [
  855. elem
  856. for is_dynamic, elem in dom_ops + url_ops
  857. if is_dynamic and elem not in defaults
  858. ]
  859. kargs = [str(k) for k in defaults]
  860. func_ast: ast.FunctionDef = _prefix_names("def _(): pass") # type: ignore
  861. func_ast.name = f"<builder:{self.rule!r}>"
  862. func_ast.args.args.append(ast.arg(".self", None))
  863. for arg in pargs + kargs:
  864. func_ast.args.args.append(ast.arg(arg, None))
  865. func_ast.args.kwarg = ast.arg(".kwargs", None)
  866. for _ in kargs:
  867. func_ast.args.defaults.append(ast.Str(""))
  868. func_ast.body = body
  869. # use `ast.parse` instead of `ast.Module` for better portability
  870. # Python 3.8 changes the signature of `ast.Module`
  871. module = ast.parse("")
  872. module.body = [func_ast]
  873. # mark everything as on line 1, offset 0
  874. # less error-prone than `ast.fix_missing_locations`
  875. # bad line numbers cause an assert to fail in debug builds
  876. for node in ast.walk(module):
  877. if "lineno" in node._attributes:
  878. node.lineno = 1
  879. if "col_offset" in node._attributes:
  880. node.col_offset = 0
  881. code = compile(module, "<werkzeug routing>", "exec")
  882. return self._get_func_code(code, func_ast.name)
  883. def build(
  884. self, values: t.Mapping[str, t.Any], append_unknown: bool = True
  885. ) -> t.Optional[t.Tuple[str, str]]:
  886. """Assembles the relative url for that rule and the subdomain.
  887. If building doesn't work for some reasons `None` is returned.
  888. :internal:
  889. """
  890. try:
  891. if append_unknown:
  892. return self._build_unknown(**values)
  893. else:
  894. return self._build(**values)
  895. except ValidationError:
  896. return None
  897. def provides_defaults_for(self, rule: "Rule") -> bool:
  898. """Check if this rule has defaults for a given rule.
  899. :internal:
  900. """
  901. return bool(
  902. not self.build_only
  903. and self.defaults
  904. and self.endpoint == rule.endpoint
  905. and self != rule
  906. and self.arguments == rule.arguments
  907. )
  908. def suitable_for(
  909. self, values: t.Mapping[str, t.Any], method: t.Optional[str] = None
  910. ) -> bool:
  911. """Check if the dict of values has enough data for url generation.
  912. :internal:
  913. """
  914. # if a method was given explicitly and that method is not supported
  915. # by this rule, this rule is not suitable.
  916. if (
  917. method is not None
  918. and self.methods is not None
  919. and method not in self.methods
  920. ):
  921. return False
  922. defaults = self.defaults or ()
  923. # all arguments required must be either in the defaults dict or
  924. # the value dictionary otherwise it's not suitable
  925. for key in self.arguments:
  926. if key not in defaults and key not in values:
  927. return False
  928. # in case defaults are given we ensure that either the value was
  929. # skipped or the value is the same as the default value.
  930. if defaults:
  931. for key, value in defaults.items():
  932. if key in values and value != values[key]:
  933. return False
  934. return True
  935. def match_compare_key(
  936. self,
  937. ) -> t.Tuple[bool, int, t.Iterable[t.Tuple[int, int]], int, t.Iterable[int]]:
  938. """The match compare key for sorting.
  939. Current implementation:
  940. 1. rules without any arguments come first for performance
  941. reasons only as we expect them to match faster and some
  942. common ones usually don't have any arguments (index pages etc.)
  943. 2. rules with more static parts come first so the second argument
  944. is the negative length of the number of the static weights.
  945. 3. we order by static weights, which is a combination of index
  946. and length
  947. 4. The more complex rules come first so the next argument is the
  948. negative length of the number of argument weights.
  949. 5. lastly we order by the actual argument weights.
  950. :internal:
  951. """
  952. return (
  953. bool(self.arguments),
  954. -len(self._static_weights),
  955. self._static_weights,
  956. -len(self._argument_weights),
  957. self._argument_weights,
  958. )
  959. def build_compare_key(self) -> t.Tuple[int, int, int]:
  960. """The build compare key for sorting.
  961. :internal:
  962. """
  963. return (1 if self.alias else 0, -len(self.arguments), -len(self.defaults or ()))
  964. def __eq__(self, other: object) -> bool:
  965. return isinstance(other, type(self)) and self._trace == other._trace
  966. __hash__ = None # type: ignore
  967. def __str__(self) -> str:
  968. return self.rule
  969. def __repr__(self) -> str:
  970. if self.map is None:
  971. return f"<{type(self).__name__} (unbound)>"
  972. parts = []
  973. for is_dynamic, data in self._trace:
  974. if is_dynamic:
  975. parts.append(f"<{data}>")
  976. else:
  977. parts.append(data)
  978. parts = "".join(parts).lstrip("|")
  979. methods = f" ({', '.join(self.methods)})" if self.methods is not None else ""
  980. return f"<{type(self).__name__} {parts!r}{methods} -> {self.endpoint}>"
  981. class BaseConverter:
  982. """Base class for all converters."""
  983. regex = "[^/]+"
  984. weight = 100
  985. def __init__(self, map: "Map", *args: t.Any, **kwargs: t.Any) -> None:
  986. self.map = map
  987. def to_python(self, value: str) -> t.Any:
  988. return value
  989. def to_url(self, value: t.Any) -> str:
  990. if isinstance(value, (bytes, bytearray)):
  991. return _fast_url_quote(value)
  992. return _fast_url_quote(str(value).encode(self.map.charset))
  993. class UnicodeConverter(BaseConverter):
  994. """This converter is the default converter and accepts any string but
  995. only one path segment. Thus the string can not include a slash.
  996. This is the default validator.
  997. Example::
  998. Rule('/pages/<page>'),
  999. Rule('/<string(length=2):lang_code>')
  1000. :param map: the :class:`Map`.
  1001. :param minlength: the minimum length of the string. Must be greater
  1002. or equal 1.
  1003. :param maxlength: the maximum length of the string.
  1004. :param length: the exact length of the string.
  1005. """
  1006. def __init__(
  1007. self,
  1008. map: "Map",
  1009. minlength: int = 1,
  1010. maxlength: t.Optional[int] = None,
  1011. length: t.Optional[int] = None,
  1012. ) -> None:
  1013. super().__init__(map)
  1014. if length is not None:
  1015. length_regex = f"{{{int(length)}}}"
  1016. else:
  1017. if maxlength is None:
  1018. maxlength_value = ""
  1019. else:
  1020. maxlength_value = str(int(maxlength))
  1021. length_regex = f"{{{int(minlength)},{maxlength_value}}}"
  1022. self.regex = f"[^/]{length_regex}"
  1023. class AnyConverter(BaseConverter):
  1024. """Matches one of the items provided. Items can either be Python
  1025. identifiers or strings::
  1026. Rule('/<any(about, help, imprint, class, "foo,bar"):page_name>')
  1027. :param map: the :class:`Map`.
  1028. :param items: this function accepts the possible items as positional
  1029. arguments.
  1030. """
  1031. def __init__(self, map: "Map", *items: str) -> None:
  1032. super().__init__(map)
  1033. self.regex = f"(?:{'|'.join([re.escape(x) for x in items])})"
  1034. class PathConverter(BaseConverter):
  1035. """Like the default :class:`UnicodeConverter`, but it also matches
  1036. slashes. This is useful for wikis and similar applications::
  1037. Rule('/<path:wikipage>')
  1038. Rule('/<path:wikipage>/edit')
  1039. :param map: the :class:`Map`.
  1040. """
  1041. regex = "[^/].*?"
  1042. weight = 200
  1043. class NumberConverter(BaseConverter):
  1044. """Baseclass for `IntegerConverter` and `FloatConverter`.
  1045. :internal:
  1046. """
  1047. weight = 50
  1048. num_convert: t.Callable = int
  1049. def __init__(
  1050. self,
  1051. map: "Map",
  1052. fixed_digits: int = 0,
  1053. min: t.Optional[int] = None,
  1054. max: t.Optional[int] = None,
  1055. signed: bool = False,
  1056. ) -> None:
  1057. if signed:
  1058. self.regex = self.signed_regex
  1059. super().__init__(map)
  1060. self.fixed_digits = fixed_digits
  1061. self.min = min
  1062. self.max = max
  1063. self.signed = signed
  1064. def to_python(self, value: str) -> t.Any:
  1065. if self.fixed_digits and len(value) != self.fixed_digits:
  1066. raise ValidationError()
  1067. value = self.num_convert(value)
  1068. if (self.min is not None and value < self.min) or (
  1069. self.max is not None and value > self.max
  1070. ):
  1071. raise ValidationError()
  1072. return value
  1073. def to_url(self, value: t.Any) -> str:
  1074. value = str(self.num_convert(value))
  1075. if self.fixed_digits:
  1076. value = value.zfill(self.fixed_digits)
  1077. return value
  1078. @property
  1079. def signed_regex(self) -> str:
  1080. return f"-?{self.regex}"
  1081. class IntegerConverter(NumberConverter):
  1082. """This converter only accepts integer values::
  1083. Rule("/page/<int:page>")
  1084. By default it only accepts unsigned, positive values. The ``signed``
  1085. parameter will enable signed, negative values. ::
  1086. Rule("/page/<int(signed=True):page>")
  1087. :param map: The :class:`Map`.
  1088. :param fixed_digits: The number of fixed digits in the URL. If you
  1089. set this to ``4`` for example, the rule will only match if the
  1090. URL looks like ``/0001/``. The default is variable length.
  1091. :param min: The minimal value.
  1092. :param max: The maximal value.
  1093. :param signed: Allow signed (negative) values.
  1094. .. versionadded:: 0.15
  1095. The ``signed`` parameter.
  1096. """
  1097. regex = r"\d+"
  1098. class FloatConverter(NumberConverter):
  1099. """This converter only accepts floating point values::
  1100. Rule("/probability/<float:probability>")
  1101. By default it only accepts unsigned, positive values. The ``signed``
  1102. parameter will enable signed, negative values. ::
  1103. Rule("/offset/<float(signed=True):offset>")
  1104. :param map: The :class:`Map`.
  1105. :param min: The minimal value.
  1106. :param max: The maximal value.
  1107. :param signed: Allow signed (negative) values.
  1108. .. versionadded:: 0.15
  1109. The ``signed`` parameter.
  1110. """
  1111. regex = r"\d+\.\d+"
  1112. num_convert = float
  1113. def __init__(
  1114. self,
  1115. map: "Map",
  1116. min: t.Optional[float] = None,
  1117. max: t.Optional[float] = None,
  1118. signed: bool = False,
  1119. ) -> None:
  1120. super().__init__(map, min=min, max=max, signed=signed) # type: ignore
  1121. class UUIDConverter(BaseConverter):
  1122. """This converter only accepts UUID strings::
  1123. Rule('/object/<uuid:identifier>')
  1124. .. versionadded:: 0.10
  1125. :param map: the :class:`Map`.
  1126. """
  1127. regex = (
  1128. r"[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-"
  1129. r"[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}"
  1130. )
  1131. def to_python(self, value: str) -> uuid.UUID:
  1132. return uuid.UUID(value)
  1133. def to_url(self, value: uuid.UUID) -> str:
  1134. return str(value)
  1135. #: the default converter mapping for the map.
  1136. DEFAULT_CONVERTERS: t.Mapping[str, t.Type[BaseConverter]] = {
  1137. "default": UnicodeConverter,
  1138. "string": UnicodeConverter,
  1139. "any": AnyConverter,
  1140. "path": PathConverter,
  1141. "int": IntegerConverter,
  1142. "float": FloatConverter,
  1143. "uuid": UUIDConverter,
  1144. }
  1145. class Map:
  1146. """The map class stores all the URL rules and some configuration
  1147. parameters. Some of the configuration values are only stored on the
  1148. `Map` instance since those affect all rules, others are just defaults
  1149. and can be overridden for each rule. Note that you have to specify all
  1150. arguments besides the `rules` as keyword arguments!
  1151. :param rules: sequence of url rules for this map.
  1152. :param default_subdomain: The default subdomain for rules without a
  1153. subdomain defined.
  1154. :param charset: charset of the url. defaults to ``"utf-8"``
  1155. :param strict_slashes: If a rule ends with a slash but the matched
  1156. URL does not, redirect to the URL with a trailing slash.
  1157. :param merge_slashes: Merge consecutive slashes when matching or
  1158. building URLs. Matches will redirect to the normalized URL.
  1159. Slashes in variable parts are not merged.
  1160. :param redirect_defaults: This will redirect to the default rule if it
  1161. wasn't visited that way. This helps creating
  1162. unique URLs.
  1163. :param converters: A dict of converters that adds additional converters
  1164. to the list of converters. If you redefine one
  1165. converter this will override the original one.
  1166. :param sort_parameters: If set to `True` the url parameters are sorted.
  1167. See `url_encode` for more details.
  1168. :param sort_key: The sort key function for `url_encode`.
  1169. :param encoding_errors: the error method to use for decoding
  1170. :param host_matching: if set to `True` it enables the host matching
  1171. feature and disables the subdomain one. If
  1172. enabled the `host` parameter to rules is used
  1173. instead of the `subdomain` one.
  1174. .. versionchanged:: 1.0
  1175. If ``url_scheme`` is ``ws`` or ``wss``, only WebSocket rules
  1176. will match.
  1177. .. versionchanged:: 1.0
  1178. Added ``merge_slashes``.
  1179. .. versionchanged:: 0.7
  1180. Added ``encoding_errors`` and ``host_matching``.
  1181. .. versionchanged:: 0.5
  1182. Added ``sort_parameters`` and ``sort_key``.
  1183. """
  1184. #: A dict of default converters to be used.
  1185. default_converters = ImmutableDict(DEFAULT_CONVERTERS)
  1186. #: The type of lock to use when updating.
  1187. #:
  1188. #: .. versionadded:: 1.0
  1189. lock_class = Lock
  1190. def __init__(
  1191. self,
  1192. rules: t.Optional[t.Iterable[RuleFactory]] = None,
  1193. default_subdomain: str = "",
  1194. charset: str = "utf-8",
  1195. strict_slashes: bool = True,
  1196. merge_slashes: bool = True,
  1197. redirect_defaults: bool = True,
  1198. converters: t.Optional[t.Mapping[str, t.Type[BaseConverter]]] = None,
  1199. sort_parameters: bool = False,
  1200. sort_key: t.Optional[t.Callable[[t.Any], t.Any]] = None,
  1201. encoding_errors: str = "replace",
  1202. host_matching: bool = False,
  1203. ) -> None:
  1204. self._rules: t.List[Rule] = []
  1205. self._rules_by_endpoint: t.Dict[str, t.List[Rule]] = {}
  1206. self._remap = True
  1207. self._remap_lock = self.lock_class()
  1208. self.default_subdomain = default_subdomain
  1209. self.charset = charset
  1210. self.encoding_errors = encoding_errors
  1211. self.strict_slashes = strict_slashes
  1212. self.merge_slashes = merge_slashes
  1213. self.redirect_defaults = redirect_defaults
  1214. self.host_matching = host_matching
  1215. self.converters = self.default_converters.copy()
  1216. if converters:
  1217. self.converters.update(converters)
  1218. self.sort_parameters = sort_parameters
  1219. self.sort_key = sort_key
  1220. for rulefactory in rules or ():
  1221. self.add(rulefactory)
  1222. def is_endpoint_expecting(self, endpoint: str, *arguments: str) -> bool:
  1223. """Iterate over all rules and check if the endpoint expects
  1224. the arguments provided. This is for example useful if you have
  1225. some URLs that expect a language code and others that do not and
  1226. you want to wrap the builder a bit so that the current language
  1227. code is automatically added if not provided but endpoints expect
  1228. it.
  1229. :param endpoint: the endpoint to check.
  1230. :param arguments: this function accepts one or more arguments
  1231. as positional arguments. Each one of them is
  1232. checked.
  1233. """
  1234. self.update()
  1235. arguments = set(arguments)
  1236. for rule in self._rules_by_endpoint[endpoint]:
  1237. if arguments.issubset(rule.arguments):
  1238. return True
  1239. return False
  1240. def iter_rules(self, endpoint: t.Optional[str] = None) -> t.Iterator[Rule]:
  1241. """Iterate over all rules or the rules of an endpoint.
  1242. :param endpoint: if provided only the rules for that endpoint
  1243. are returned.
  1244. :return: an iterator
  1245. """
  1246. self.update()
  1247. if endpoint is not None:
  1248. return iter(self._rules_by_endpoint[endpoint])
  1249. return iter(self._rules)
  1250. def add(self, rulefactory: RuleFactory) -> None:
  1251. """Add a new rule or factory to the map and bind it. Requires that the
  1252. rule is not bound to another map.
  1253. :param rulefactory: a :class:`Rule` or :class:`RuleFactory`
  1254. """
  1255. for rule in rulefactory.get_rules(self):
  1256. rule.bind(self)
  1257. self._rules.append(rule)
  1258. self._rules_by_endpoint.setdefault(rule.endpoint, []).append(rule)
  1259. self._remap = True
  1260. def bind(
  1261. self,
  1262. server_name: str,
  1263. script_name: t.Optional[str] = None,
  1264. subdomain: t.Optional[str] = None,
  1265. url_scheme: str = "http",
  1266. default_method: str = "GET",
  1267. path_info: t.Optional[str] = None,
  1268. query_args: t.Optional[t.Union[t.Mapping[str, t.Any], str]] = None,
  1269. ) -> "MapAdapter":
  1270. """Return a new :class:`MapAdapter` with the details specified to the
  1271. call. Note that `script_name` will default to ``'/'`` if not further
  1272. specified or `None`. The `server_name` at least is a requirement
  1273. because the HTTP RFC requires absolute URLs for redirects and so all
  1274. redirect exceptions raised by Werkzeug will contain the full canonical
  1275. URL.
  1276. If no path_info is passed to :meth:`match` it will use the default path
  1277. info passed to bind. While this doesn't really make sense for
  1278. manual bind calls, it's useful if you bind a map to a WSGI
  1279. environment which already contains the path info.
  1280. `subdomain` will default to the `default_subdomain` for this map if
  1281. no defined. If there is no `default_subdomain` you cannot use the
  1282. subdomain feature.
  1283. .. versionchanged:: 1.0
  1284. If ``url_scheme`` is ``ws`` or ``wss``, only WebSocket rules
  1285. will match.
  1286. .. versionchanged:: 0.15
  1287. ``path_info`` defaults to ``'/'`` if ``None``.
  1288. .. versionchanged:: 0.8
  1289. ``query_args`` can be a string.
  1290. .. versionchanged:: 0.7
  1291. Added ``query_args``.
  1292. """
  1293. server_name = server_name.lower()
  1294. if self.host_matching:
  1295. if subdomain is not None:
  1296. raise RuntimeError("host matching enabled and a subdomain was provided")
  1297. elif subdomain is None:
  1298. subdomain = self.default_subdomain
  1299. if script_name is None:
  1300. script_name = "/"
  1301. if path_info is None:
  1302. path_info = "/"
  1303. try:
  1304. server_name = _encode_idna(server_name) # type: ignore
  1305. except UnicodeError as e:
  1306. raise BadHost() from e
  1307. return MapAdapter(
  1308. self,
  1309. server_name,
  1310. script_name,
  1311. subdomain,
  1312. url_scheme,
  1313. path_info,
  1314. default_method,
  1315. query_args,
  1316. )
  1317. def bind_to_environ(
  1318. self,
  1319. environ: t.Union["WSGIEnvironment", "Request"],
  1320. server_name: t.Optional[str] = None,
  1321. subdomain: t.Optional[str] = None,
  1322. ) -> "MapAdapter":
  1323. """Like :meth:`bind` but you can pass it an WSGI environment and it
  1324. will fetch the information from that dictionary. Note that because of
  1325. limitations in the protocol there is no way to get the current
  1326. subdomain and real `server_name` from the environment. If you don't
  1327. provide it, Werkzeug will use `SERVER_NAME` and `SERVER_PORT` (or
  1328. `HTTP_HOST` if provided) as used `server_name` with disabled subdomain
  1329. feature.
  1330. If `subdomain` is `None` but an environment and a server name is
  1331. provided it will calculate the current subdomain automatically.
  1332. Example: `server_name` is ``'example.com'`` and the `SERVER_NAME`
  1333. in the wsgi `environ` is ``'staging.dev.example.com'`` the calculated
  1334. subdomain will be ``'staging.dev'``.
  1335. If the object passed as environ has an environ attribute, the value of
  1336. this attribute is used instead. This allows you to pass request
  1337. objects. Additionally `PATH_INFO` added as a default of the
  1338. :class:`MapAdapter` so that you don't have to pass the path info to
  1339. the match method.
  1340. .. versionchanged:: 1.0.0
  1341. If the passed server name specifies port 443, it will match
  1342. if the incoming scheme is ``https`` without a port.
  1343. .. versionchanged:: 1.0.0
  1344. A warning is shown when the passed server name does not
  1345. match the incoming WSGI server name.
  1346. .. versionchanged:: 0.8
  1347. This will no longer raise a ValueError when an unexpected server
  1348. name was passed.
  1349. .. versionchanged:: 0.5
  1350. previously this method accepted a bogus `calculate_subdomain`
  1351. parameter that did not have any effect. It was removed because
  1352. of that.
  1353. :param environ: a WSGI environment.
  1354. :param server_name: an optional server name hint (see above).
  1355. :param subdomain: optionally the current subdomain (see above).
  1356. """
  1357. env = _get_environ(environ)
  1358. wsgi_server_name = get_host(env).lower()
  1359. scheme = env["wsgi.url_scheme"]
  1360. upgrade = any(
  1361. v.strip() == "upgrade"
  1362. for v in env.get("HTTP_CONNECTION", "").lower().split(",")
  1363. )
  1364. if upgrade and env.get("HTTP_UPGRADE", "").lower() == "websocket":
  1365. scheme = "wss" if scheme == "https" else "ws"
  1366. if server_name is None:
  1367. server_name = wsgi_server_name
  1368. else:
  1369. server_name = server_name.lower()
  1370. # strip standard port to match get_host()
  1371. if scheme in {"http", "ws"} and server_name.endswith(":80"):
  1372. server_name = server_name[:-3]
  1373. elif scheme in {"https", "wss"} and server_name.endswith(":443"):
  1374. server_name = server_name[:-4]
  1375. if subdomain is None and not self.host_matching:
  1376. cur_server_name = wsgi_server_name.split(".")
  1377. real_server_name = server_name.split(".")
  1378. offset = -len(real_server_name)
  1379. if cur_server_name[offset:] != real_server_name:
  1380. # This can happen even with valid configs if the server was
  1381. # accessed directly by IP address under some situations.
  1382. # Instead of raising an exception like in Werkzeug 0.7 or
  1383. # earlier we go by an invalid subdomain which will result
  1384. # in a 404 error on matching.
  1385. warnings.warn(
  1386. f"Current server name {wsgi_server_name!r} doesn't match configured"
  1387. f" server name {server_name!r}",
  1388. stacklevel=2,
  1389. )
  1390. subdomain = "<invalid>"
  1391. else:
  1392. subdomain = ".".join(filter(None, cur_server_name[:offset]))
  1393. def _get_wsgi_string(name: str) -> t.Optional[str]:
  1394. val = env.get(name)
  1395. if val is not None:
  1396. return _wsgi_decoding_dance(val, self.charset)
  1397. return None
  1398. script_name = _get_wsgi_string("SCRIPT_NAME")
  1399. path_info = _get_wsgi_string("PATH_INFO")
  1400. query_args = _get_wsgi_string("QUERY_STRING")
  1401. return Map.bind(
  1402. self,
  1403. server_name,
  1404. script_name,
  1405. subdomain,
  1406. scheme,
  1407. env["REQUEST_METHOD"],
  1408. path_info,
  1409. query_args=query_args,
  1410. )
  1411. def update(self) -> None:
  1412. """Called before matching and building to keep the compiled rules
  1413. in the correct order after things changed.
  1414. """
  1415. if not self._remap:
  1416. return
  1417. with self._remap_lock:
  1418. if not self._remap:
  1419. return
  1420. self._rules.sort(key=lambda x: x.match_compare_key())
  1421. for rules in self._rules_by_endpoint.values():
  1422. rules.sort(key=lambda x: x.build_compare_key())
  1423. self._remap = False
  1424. def __repr__(self) -> str:
  1425. rules = self.iter_rules()
  1426. return f"{type(self).__name__}({pformat(list(rules))})"
  1427. class MapAdapter:
  1428. """Returned by :meth:`Map.bind` or :meth:`Map.bind_to_environ` and does
  1429. the URL matching and building based on runtime information.
  1430. """
  1431. def __init__(
  1432. self,
  1433. map: Map,
  1434. server_name: str,
  1435. script_name: str,
  1436. subdomain: t.Optional[str],
  1437. url_scheme: str,
  1438. path_info: str,
  1439. default_method: str,
  1440. query_args: t.Optional[t.Union[t.Mapping[str, t.Any], str]] = None,
  1441. ):
  1442. self.map = map
  1443. self.server_name = _to_str(server_name)
  1444. script_name = _to_str(script_name)
  1445. if not script_name.endswith("/"):
  1446. script_name += "/"
  1447. self.script_name = script_name
  1448. self.subdomain = _to_str(subdomain)
  1449. self.url_scheme = _to_str(url_scheme)
  1450. self.path_info = _to_str(path_info)
  1451. self.default_method = _to_str(default_method)
  1452. self.query_args = query_args
  1453. self.websocket = self.url_scheme in {"ws", "wss"}
  1454. def dispatch(
  1455. self,
  1456. view_func: t.Callable[[str, t.Mapping[str, t.Any]], "WSGIApplication"],
  1457. path_info: t.Optional[str] = None,
  1458. method: t.Optional[str] = None,
  1459. catch_http_exceptions: bool = False,
  1460. ) -> "WSGIApplication":
  1461. """Does the complete dispatching process. `view_func` is called with
  1462. the endpoint and a dict with the values for the view. It should
  1463. look up the view function, call it, and return a response object
  1464. or WSGI application. http exceptions are not caught by default
  1465. so that applications can display nicer error messages by just
  1466. catching them by hand. If you want to stick with the default
  1467. error messages you can pass it ``catch_http_exceptions=True`` and
  1468. it will catch the http exceptions.
  1469. Here a small example for the dispatch usage::
  1470. from werkzeug.wrappers import Request, Response
  1471. from werkzeug.wsgi import responder
  1472. from werkzeug.routing import Map, Rule
  1473. def on_index(request):
  1474. return Response('Hello from the index')
  1475. url_map = Map([Rule('/', endpoint='index')])
  1476. views = {'index': on_index}
  1477. @responder
  1478. def application(environ, start_response):
  1479. request = Request(environ)
  1480. urls = url_map.bind_to_environ(environ)
  1481. return urls.dispatch(lambda e, v: views[e](request, **v),
  1482. catch_http_exceptions=True)
  1483. Keep in mind that this method might return exception objects, too, so
  1484. use :class:`Response.force_type` to get a response object.
  1485. :param view_func: a function that is called with the endpoint as
  1486. first argument and the value dict as second. Has
  1487. to dispatch to the actual view function with this
  1488. information. (see above)
  1489. :param path_info: the path info to use for matching. Overrides the
  1490. path info specified on binding.
  1491. :param method: the HTTP method used for matching. Overrides the
  1492. method specified on binding.
  1493. :param catch_http_exceptions: set to `True` to catch any of the
  1494. werkzeug :class:`HTTPException`\\s.
  1495. """
  1496. try:
  1497. try:
  1498. endpoint, args = self.match(path_info, method)
  1499. except RequestRedirect as e:
  1500. return e
  1501. return view_func(endpoint, args)
  1502. except HTTPException as e:
  1503. if catch_http_exceptions:
  1504. return e
  1505. raise
  1506. @typing.overload
  1507. def match( # type: ignore
  1508. self,
  1509. path_info: t.Optional[str] = None,
  1510. method: t.Optional[str] = None,
  1511. return_rule: "te.Literal[False]" = False,
  1512. query_args: t.Optional[t.Union[t.Mapping[str, t.Any], str]] = None,
  1513. websocket: t.Optional[bool] = None,
  1514. ) -> t.Tuple[str, t.Mapping[str, t.Any]]:
  1515. ...
  1516. @typing.overload
  1517. def match(
  1518. self,
  1519. path_info: t.Optional[str] = None,
  1520. method: t.Optional[str] = None,
  1521. return_rule: "te.Literal[True]" = True,
  1522. query_args: t.Optional[t.Union[t.Mapping[str, t.Any], str]] = None,
  1523. websocket: t.Optional[bool] = None,
  1524. ) -> t.Tuple[Rule, t.Mapping[str, t.Any]]:
  1525. ...
  1526. def match(
  1527. self,
  1528. path_info: t.Optional[str] = None,
  1529. method: t.Optional[str] = None,
  1530. return_rule: bool = False,
  1531. query_args: t.Optional[t.Union[t.Mapping[str, t.Any], str]] = None,
  1532. websocket: t.Optional[bool] = None,
  1533. ) -> t.Tuple[t.Union[str, Rule], t.Mapping[str, t.Any]]:
  1534. """The usage is simple: you just pass the match method the current
  1535. path info as well as the method (which defaults to `GET`). The
  1536. following things can then happen:
  1537. - you receive a `NotFound` exception that indicates that no URL is
  1538. matching. A `NotFound` exception is also a WSGI application you
  1539. can call to get a default page not found page (happens to be the
  1540. same object as `werkzeug.exceptions.NotFound`)
  1541. - you receive a `MethodNotAllowed` exception that indicates that there
  1542. is a match for this URL but not for the current request method.
  1543. This is useful for RESTful applications.
  1544. - you receive a `RequestRedirect` exception with a `new_url`
  1545. attribute. This exception is used to notify you about a request
  1546. Werkzeug requests from your WSGI application. This is for example the
  1547. case if you request ``/foo`` although the correct URL is ``/foo/``
  1548. You can use the `RequestRedirect` instance as response-like object
  1549. similar to all other subclasses of `HTTPException`.
  1550. - you receive a ``WebsocketMismatch`` exception if the only
  1551. match is a WebSocket rule but the bind is an HTTP request, or
  1552. if the match is an HTTP rule but the bind is a WebSocket
  1553. request.
  1554. - you get a tuple in the form ``(endpoint, arguments)`` if there is
  1555. a match (unless `return_rule` is True, in which case you get a tuple
  1556. in the form ``(rule, arguments)``)
  1557. If the path info is not passed to the match method the default path
  1558. info of the map is used (defaults to the root URL if not defined
  1559. explicitly).
  1560. All of the exceptions raised are subclasses of `HTTPException` so they
  1561. can be used as WSGI responses. They will all render generic error or
  1562. redirect pages.
  1563. Here is a small example for matching:
  1564. >>> m = Map([
  1565. ... Rule('/', endpoint='index'),
  1566. ... Rule('/downloads/', endpoint='downloads/index'),
  1567. ... Rule('/downloads/<int:id>', endpoint='downloads/show')
  1568. ... ])
  1569. >>> urls = m.bind("example.com", "/")
  1570. >>> urls.match("/", "GET")
  1571. ('index', {})
  1572. >>> urls.match("/downloads/42")
  1573. ('downloads/show', {'id': 42})
  1574. And here is what happens on redirect and missing URLs:
  1575. >>> urls.match("/downloads")
  1576. Traceback (most recent call last):
  1577. ...
  1578. RequestRedirect: http://example.com/downloads/
  1579. >>> urls.match("/missing")
  1580. Traceback (most recent call last):
  1581. ...
  1582. NotFound: 404 Not Found
  1583. :param path_info: the path info to use for matching. Overrides the
  1584. path info specified on binding.
  1585. :param method: the HTTP method used for matching. Overrides the
  1586. method specified on binding.
  1587. :param return_rule: return the rule that matched instead of just the
  1588. endpoint (defaults to `False`).
  1589. :param query_args: optional query arguments that are used for
  1590. automatic redirects as string or dictionary. It's
  1591. currently not possible to use the query arguments
  1592. for URL matching.
  1593. :param websocket: Match WebSocket instead of HTTP requests. A
  1594. websocket request has a ``ws`` or ``wss``
  1595. :attr:`url_scheme`. This overrides that detection.
  1596. .. versionadded:: 1.0
  1597. Added ``websocket``.
  1598. .. versionchanged:: 0.8
  1599. ``query_args`` can be a string.
  1600. .. versionadded:: 0.7
  1601. Added ``query_args``.
  1602. .. versionadded:: 0.6
  1603. Added ``return_rule``.
  1604. """
  1605. self.map.update()
  1606. if path_info is None:
  1607. path_info = self.path_info
  1608. else:
  1609. path_info = _to_str(path_info, self.map.charset)
  1610. if query_args is None:
  1611. query_args = self.query_args or {}
  1612. method = (method or self.default_method).upper()
  1613. if websocket is None:
  1614. websocket = self.websocket
  1615. require_redirect = False
  1616. domain_part = self.server_name if self.map.host_matching else self.subdomain
  1617. path_part = f"/{path_info.lstrip('/')}" if path_info else ""
  1618. path = f"{domain_part}|{path_part}"
  1619. have_match_for = set()
  1620. websocket_mismatch = False
  1621. for rule in self.map._rules:
  1622. try:
  1623. rv = rule.match(path, method)
  1624. except RequestPath as e:
  1625. raise RequestRedirect(
  1626. self.make_redirect_url(
  1627. url_quote(e.path_info, self.map.charset, safe="/:|+"),
  1628. query_args,
  1629. )
  1630. ) from None
  1631. except RequestAliasRedirect as e:
  1632. raise RequestRedirect(
  1633. self.make_alias_redirect_url(
  1634. path, rule.endpoint, e.matched_values, method, query_args
  1635. )
  1636. ) from None
  1637. if rv is None:
  1638. continue
  1639. if rule.methods is not None and method not in rule.methods:
  1640. have_match_for.update(rule.methods)
  1641. continue
  1642. if rule.websocket != websocket:
  1643. websocket_mismatch = True
  1644. continue
  1645. if self.map.redirect_defaults:
  1646. redirect_url = self.get_default_redirect(rule, method, rv, query_args)
  1647. if redirect_url is not None:
  1648. raise RequestRedirect(redirect_url)
  1649. if rule.redirect_to is not None:
  1650. if isinstance(rule.redirect_to, str):
  1651. def _handle_match(match: t.Match[str]) -> str:
  1652. value = rv[match.group(1)] # type: ignore
  1653. return rule._converters[match.group(1)].to_url(value)
  1654. redirect_url = _simple_rule_re.sub(_handle_match, rule.redirect_to)
  1655. else:
  1656. redirect_url = rule.redirect_to(self, **rv)
  1657. if self.subdomain:
  1658. netloc = f"{self.subdomain}.{self.server_name}"
  1659. else:
  1660. netloc = self.server_name
  1661. raise RequestRedirect(
  1662. url_join(
  1663. f"{self.url_scheme or 'http'}://{netloc}{self.script_name}",
  1664. redirect_url,
  1665. )
  1666. )
  1667. if require_redirect:
  1668. raise RequestRedirect(
  1669. self.make_redirect_url(
  1670. url_quote(path_info, self.map.charset, safe="/:|+"), query_args
  1671. )
  1672. )
  1673. if return_rule:
  1674. return rule, rv
  1675. else:
  1676. return rule.endpoint, rv
  1677. if have_match_for:
  1678. raise MethodNotAllowed(valid_methods=list(have_match_for))
  1679. if websocket_mismatch:
  1680. raise WebsocketMismatch()
  1681. raise NotFound()
  1682. def test(
  1683. self, path_info: t.Optional[str] = None, method: t.Optional[str] = None
  1684. ) -> bool:
  1685. """Test if a rule would match. Works like `match` but returns `True`
  1686. if the URL matches, or `False` if it does not exist.
  1687. :param path_info: the path info to use for matching. Overrides the
  1688. path info specified on binding.
  1689. :param method: the HTTP method used for matching. Overrides the
  1690. method specified on binding.
  1691. """
  1692. try:
  1693. self.match(path_info, method)
  1694. except RequestRedirect:
  1695. pass
  1696. except HTTPException:
  1697. return False
  1698. return True
  1699. def allowed_methods(self, path_info: t.Optional[str] = None) -> t.Iterable[str]:
  1700. """Returns the valid methods that match for a given path.
  1701. .. versionadded:: 0.7
  1702. """
  1703. try:
  1704. self.match(path_info, method="--")
  1705. except MethodNotAllowed as e:
  1706. return e.valid_methods # type: ignore
  1707. except HTTPException:
  1708. pass
  1709. return []
  1710. def get_host(self, domain_part: t.Optional[str]) -> str:
  1711. """Figures out the full host name for the given domain part. The
  1712. domain part is a subdomain in case host matching is disabled or
  1713. a full host name.
  1714. """
  1715. if self.map.host_matching:
  1716. if domain_part is None:
  1717. return self.server_name
  1718. return _to_str(domain_part, "ascii")
  1719. subdomain = domain_part
  1720. if subdomain is None:
  1721. subdomain = self.subdomain
  1722. else:
  1723. subdomain = _to_str(subdomain, "ascii")
  1724. if subdomain:
  1725. return f"{subdomain}.{self.server_name}"
  1726. else:
  1727. return self.server_name
  1728. def get_default_redirect(
  1729. self,
  1730. rule: Rule,
  1731. method: str,
  1732. values: t.MutableMapping[str, t.Any],
  1733. query_args: t.Union[t.Mapping[str, t.Any], str],
  1734. ) -> t.Optional[str]:
  1735. """A helper that returns the URL to redirect to if it finds one.
  1736. This is used for default redirecting only.
  1737. :internal:
  1738. """
  1739. assert self.map.redirect_defaults
  1740. for r in self.map._rules_by_endpoint[rule.endpoint]:
  1741. # every rule that comes after this one, including ourself
  1742. # has a lower priority for the defaults. We order the ones
  1743. # with the highest priority up for building.
  1744. if r is rule:
  1745. break
  1746. if r.provides_defaults_for(rule) and r.suitable_for(values, method):
  1747. values.update(r.defaults) # type: ignore
  1748. domain_part, path = r.build(values) # type: ignore
  1749. return self.make_redirect_url(path, query_args, domain_part=domain_part)
  1750. return None
  1751. def encode_query_args(self, query_args: t.Union[t.Mapping[str, t.Any], str]) -> str:
  1752. if not isinstance(query_args, str):
  1753. return url_encode(query_args, self.map.charset)
  1754. return query_args
  1755. def make_redirect_url(
  1756. self,
  1757. path_info: str,
  1758. query_args: t.Optional[t.Union[t.Mapping[str, t.Any], str]] = None,
  1759. domain_part: t.Optional[str] = None,
  1760. ) -> str:
  1761. """Creates a redirect URL.
  1762. :internal:
  1763. """
  1764. if query_args:
  1765. suffix = f"?{self.encode_query_args(query_args)}"
  1766. else:
  1767. suffix = ""
  1768. scheme = self.url_scheme or "http"
  1769. host = self.get_host(domain_part)
  1770. path = posixpath.join(self.script_name.strip("/"), path_info.lstrip("/"))
  1771. return f"{scheme}://{host}/{path}{suffix}"
  1772. def make_alias_redirect_url(
  1773. self,
  1774. path: str,
  1775. endpoint: str,
  1776. values: t.Mapping[str, t.Any],
  1777. method: str,
  1778. query_args: t.Union[t.Mapping[str, t.Any], str],
  1779. ) -> str:
  1780. """Internally called to make an alias redirect URL."""
  1781. url = self.build(
  1782. endpoint, values, method, append_unknown=False, force_external=True
  1783. )
  1784. if query_args:
  1785. url += f"?{self.encode_query_args(query_args)}"
  1786. assert url != path, "detected invalid alias setting. No canonical URL found"
  1787. return url
  1788. def _partial_build(
  1789. self,
  1790. endpoint: str,
  1791. values: t.Mapping[str, t.Any],
  1792. method: t.Optional[str],
  1793. append_unknown: bool,
  1794. ) -> t.Optional[t.Tuple[str, str, bool]]:
  1795. """Helper for :meth:`build`. Returns subdomain and path for the
  1796. rule that accepts this endpoint, values and method.
  1797. :internal:
  1798. """
  1799. # in case the method is none, try with the default method first
  1800. if method is None:
  1801. rv = self._partial_build(
  1802. endpoint, values, self.default_method, append_unknown
  1803. )
  1804. if rv is not None:
  1805. return rv
  1806. # Default method did not match or a specific method is passed.
  1807. # Check all for first match with matching host. If no matching
  1808. # host is found, go with first result.
  1809. first_match = None
  1810. for rule in self.map._rules_by_endpoint.get(endpoint, ()):
  1811. if rule.suitable_for(values, method):
  1812. build_rv = rule.build(values, append_unknown)
  1813. if build_rv is not None:
  1814. rv = (build_rv[0], build_rv[1], rule.websocket)
  1815. if self.map.host_matching:
  1816. if rv[0] == self.server_name:
  1817. return rv
  1818. elif first_match is None:
  1819. first_match = rv
  1820. else:
  1821. return rv
  1822. return first_match
  1823. def build(
  1824. self,
  1825. endpoint: str,
  1826. values: t.Optional[t.Mapping[str, t.Any]] = None,
  1827. method: t.Optional[str] = None,
  1828. force_external: bool = False,
  1829. append_unknown: bool = True,
  1830. url_scheme: t.Optional[str] = None,
  1831. ) -> str:
  1832. """Building URLs works pretty much the other way round. Instead of
  1833. `match` you call `build` and pass it the endpoint and a dict of
  1834. arguments for the placeholders.
  1835. The `build` function also accepts an argument called `force_external`
  1836. which, if you set it to `True` will force external URLs. Per default
  1837. external URLs (include the server name) will only be used if the
  1838. target URL is on a different subdomain.
  1839. >>> m = Map([
  1840. ... Rule('/', endpoint='index'),
  1841. ... Rule('/downloads/', endpoint='downloads/index'),
  1842. ... Rule('/downloads/<int:id>', endpoint='downloads/show')
  1843. ... ])
  1844. >>> urls = m.bind("example.com", "/")
  1845. >>> urls.build("index", {})
  1846. '/'
  1847. >>> urls.build("downloads/show", {'id': 42})
  1848. '/downloads/42'
  1849. >>> urls.build("downloads/show", {'id': 42}, force_external=True)
  1850. 'http://example.com/downloads/42'
  1851. Because URLs cannot contain non ASCII data you will always get
  1852. bytes back. Non ASCII characters are urlencoded with the
  1853. charset defined on the map instance.
  1854. Additional values are converted to strings and appended to the URL as
  1855. URL querystring parameters:
  1856. >>> urls.build("index", {'q': 'My Searchstring'})
  1857. '/?q=My+Searchstring'
  1858. When processing those additional values, lists are furthermore
  1859. interpreted as multiple values (as per
  1860. :py:class:`werkzeug.datastructures.MultiDict`):
  1861. >>> urls.build("index", {'q': ['a', 'b', 'c']})
  1862. '/?q=a&q=b&q=c'
  1863. Passing a ``MultiDict`` will also add multiple values:
  1864. >>> urls.build("index", MultiDict((('p', 'z'), ('q', 'a'), ('q', 'b'))))
  1865. '/?p=z&q=a&q=b'
  1866. If a rule does not exist when building a `BuildError` exception is
  1867. raised.
  1868. The build method accepts an argument called `method` which allows you
  1869. to specify the method you want to have an URL built for if you have
  1870. different methods for the same endpoint specified.
  1871. :param endpoint: the endpoint of the URL to build.
  1872. :param values: the values for the URL to build. Unhandled values are
  1873. appended to the URL as query parameters.
  1874. :param method: the HTTP method for the rule if there are different
  1875. URLs for different methods on the same endpoint.
  1876. :param force_external: enforce full canonical external URLs. If the URL
  1877. scheme is not provided, this will generate
  1878. a protocol-relative URL.
  1879. :param append_unknown: unknown parameters are appended to the generated
  1880. URL as query string argument. Disable this
  1881. if you want the builder to ignore those.
  1882. :param url_scheme: Scheme to use in place of the bound
  1883. :attr:`url_scheme`.
  1884. .. versionchanged:: 2.0
  1885. Added the ``url_scheme`` parameter.
  1886. .. versionadded:: 0.6
  1887. Added the ``append_unknown`` parameter.
  1888. """
  1889. self.map.update()
  1890. if values:
  1891. if isinstance(values, MultiDict):
  1892. values = {
  1893. k: (v[0] if len(v) == 1 else v)
  1894. for k, v in dict.items(values)
  1895. if len(v) != 0
  1896. }
  1897. else: # plain dict
  1898. values = {k: v for k, v in values.items() if v is not None}
  1899. else:
  1900. values = {}
  1901. rv = self._partial_build(endpoint, values, method, append_unknown)
  1902. if rv is None:
  1903. raise BuildError(endpoint, values, method, self)
  1904. domain_part, path, websocket = rv
  1905. host = self.get_host(domain_part)
  1906. if url_scheme is None:
  1907. url_scheme = self.url_scheme
  1908. # Always build WebSocket routes with the scheme (browsers
  1909. # require full URLs). If bound to a WebSocket, ensure that HTTP
  1910. # routes are built with an HTTP scheme.
  1911. secure = url_scheme in {"https", "wss"}
  1912. if websocket:
  1913. force_external = True
  1914. url_scheme = "wss" if secure else "ws"
  1915. elif url_scheme:
  1916. url_scheme = "https" if secure else "http"
  1917. # shortcut this.
  1918. if not force_external and (
  1919. (self.map.host_matching and host == self.server_name)
  1920. or (not self.map.host_matching and domain_part == self.subdomain)
  1921. ):
  1922. return f"{self.script_name.rstrip('/')}/{path.lstrip('/')}"
  1923. scheme = f"{url_scheme}:" if url_scheme else ""
  1924. return f"{scheme}//{host}{self.script_name[:-1]}/{path.lstrip('/')}"