routing.py 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342
  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. q = '?'
  441. params = self._encode_query_vars(kwargs)
  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`` he 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. .. versionadded:: 1.0
  536. Added ``websocket``.
  537. .. versionadded:: 1.0
  538. Added ``merge_slashes``.
  539. .. versionadded:: 0.7
  540. Added ``alias`` and ``host``.
  541. .. versionchanged:: 0.6.1
  542. ``HEAD`` is added to ``methods`` if ``GET`` is present.
  543. """
  544. def __init__(
  545. self,
  546. string: str,
  547. defaults: t.Optional[t.Mapping[str, t.Any]] = None,
  548. subdomain: t.Optional[str] = None,
  549. methods: t.Optional[t.Iterable[str]] = None,
  550. build_only: bool = False,
  551. endpoint: t.Optional[str] = None,
  552. strict_slashes: t.Optional[bool] = None,
  553. merge_slashes: t.Optional[bool] = None,
  554. redirect_to: t.Optional[t.Union[str, t.Callable[..., str]]] = None,
  555. alias: bool = False,
  556. host: t.Optional[str] = None,
  557. websocket: bool = False,
  558. ) -> None:
  559. if not string.startswith("/"):
  560. raise ValueError("urls must start with a leading slash")
  561. self.rule = string
  562. self.is_leaf = not string.endswith("/")
  563. self.map: "Map" = None # type: ignore
  564. self.strict_slashes = strict_slashes
  565. self.merge_slashes = merge_slashes
  566. self.subdomain = subdomain
  567. self.host = host
  568. self.defaults = defaults
  569. self.build_only = build_only
  570. self.alias = alias
  571. self.websocket = websocket
  572. if methods is not None:
  573. if isinstance(methods, str):
  574. raise TypeError("'methods' should be a list of strings.")
  575. methods = {x.upper() for x in methods}
  576. if "HEAD" not in methods and "GET" in methods:
  577. methods.add("HEAD")
  578. if websocket and methods - {"GET", "HEAD", "OPTIONS"}:
  579. raise ValueError(
  580. "WebSocket rules can only use 'GET', 'HEAD', and 'OPTIONS' methods."
  581. )
  582. self.methods = methods
  583. self.endpoint: str = endpoint # type: ignore
  584. self.redirect_to = redirect_to
  585. if defaults:
  586. self.arguments = set(map(str, defaults))
  587. else:
  588. self.arguments = set()
  589. self._trace: t.List[t.Tuple[bool, str]] = []
  590. def empty(self) -> "Rule":
  591. """
  592. Return an unbound copy of this rule.
  593. This can be useful if want to reuse an already bound URL for another
  594. map. See ``get_empty_kwargs`` to override what keyword arguments are
  595. provided to the new copy.
  596. """
  597. return type(self)(self.rule, **self.get_empty_kwargs())
  598. def get_empty_kwargs(self) -> t.Mapping[str, t.Any]:
  599. """
  600. Provides kwargs for instantiating empty copy with empty()
  601. Use this method to provide custom keyword arguments to the subclass of
  602. ``Rule`` when calling ``some_rule.empty()``. Helpful when the subclass
  603. has custom keyword arguments that are needed at instantiation.
  604. Must return a ``dict`` that will be provided as kwargs to the new
  605. instance of ``Rule``, following the initial ``self.rule`` value which
  606. is always provided as the first, required positional argument.
  607. """
  608. defaults = None
  609. if self.defaults:
  610. defaults = dict(self.defaults)
  611. return dict(
  612. defaults=defaults,
  613. subdomain=self.subdomain,
  614. methods=self.methods,
  615. build_only=self.build_only,
  616. endpoint=self.endpoint,
  617. strict_slashes=self.strict_slashes,
  618. redirect_to=self.redirect_to,
  619. alias=self.alias,
  620. host=self.host,
  621. )
  622. def get_rules(self, map: "Map") -> t.Iterator["Rule"]:
  623. yield self
  624. def refresh(self) -> None:
  625. """Rebinds and refreshes the URL. Call this if you modified the
  626. rule in place.
  627. :internal:
  628. """
  629. self.bind(self.map, rebind=True)
  630. def bind(self, map: "Map", rebind: bool = False) -> None:
  631. """Bind the url to a map and create a regular expression based on
  632. the information from the rule itself and the defaults from the map.
  633. :internal:
  634. """
  635. if self.map is not None and not rebind:
  636. raise RuntimeError(f"url rule {self!r} already bound to map {self.map!r}")
  637. self.map = map
  638. if self.strict_slashes is None:
  639. self.strict_slashes = map.strict_slashes
  640. if self.merge_slashes is None:
  641. self.merge_slashes = map.merge_slashes
  642. if self.subdomain is None:
  643. self.subdomain = map.default_subdomain
  644. self.compile()
  645. def get_converter(
  646. self,
  647. variable_name: str,
  648. converter_name: str,
  649. args: t.Tuple,
  650. kwargs: t.Mapping[str, t.Any],
  651. ) -> "BaseConverter":
  652. """Looks up the converter for the given parameter.
  653. .. versionadded:: 0.9
  654. """
  655. if converter_name not in self.map.converters:
  656. raise LookupError(f"the converter {converter_name!r} does not exist")
  657. return self.map.converters[converter_name](self.map, *args, **kwargs)
  658. def _encode_query_vars(self, query_vars: t.Mapping[str, t.Any]) -> str:
  659. return url_encode(
  660. query_vars,
  661. charset=self.map.charset,
  662. sort=self.map.sort_parameters,
  663. key=self.map.sort_key,
  664. )
  665. def compile(self) -> None:
  666. """Compiles the regular expression and stores it."""
  667. assert self.map is not None, "rule not bound"
  668. if self.map.host_matching:
  669. domain_rule = self.host or ""
  670. else:
  671. domain_rule = self.subdomain or ""
  672. self._trace = []
  673. self._converters: t.Dict[str, "BaseConverter"] = {}
  674. self._static_weights: t.List[t.Tuple[int, int]] = []
  675. self._argument_weights: t.List[int] = []
  676. regex_parts = []
  677. def _build_regex(rule: str) -> None:
  678. index = 0
  679. for converter, arguments, variable in parse_rule(rule):
  680. if converter is None:
  681. for match in re.finditer(r"/+|[^/]+", variable):
  682. part = match.group(0)
  683. if part.startswith("/"):
  684. if self.merge_slashes:
  685. regex_parts.append(r"/+?")
  686. self._trace.append((False, "/"))
  687. else:
  688. regex_parts.append(part)
  689. self._trace.append((False, part))
  690. continue
  691. self._trace.append((False, part))
  692. regex_parts.append(re.escape(part))
  693. if part:
  694. self._static_weights.append((index, -len(part)))
  695. else:
  696. if arguments:
  697. c_args, c_kwargs = parse_converter_args(arguments)
  698. else:
  699. c_args = ()
  700. c_kwargs = {}
  701. convobj = self.get_converter(variable, converter, c_args, c_kwargs)
  702. regex_parts.append(f"(?P<{variable}>{convobj.regex})")
  703. self._converters[variable] = convobj
  704. self._trace.append((True, variable))
  705. self._argument_weights.append(convobj.weight)
  706. self.arguments.add(str(variable))
  707. index = index + 1
  708. _build_regex(domain_rule)
  709. regex_parts.append("\\|")
  710. self._trace.append((False, "|"))
  711. _build_regex(self.rule if self.is_leaf else self.rule.rstrip("/"))
  712. if not self.is_leaf:
  713. self._trace.append((False, "/"))
  714. self._build: t.Callable[..., t.Tuple[str, str]]
  715. self._build = self._compile_builder(False).__get__(self, None) # type: ignore
  716. self._build_unknown: t.Callable[..., t.Tuple[str, str]]
  717. self._build_unknown = self._compile_builder(True).__get__( # type: ignore
  718. self, None
  719. )
  720. if self.build_only:
  721. return
  722. if not (self.is_leaf and self.strict_slashes):
  723. reps = "*" if self.merge_slashes else "?"
  724. tail = f"(?<!/)(?P<__suffix__>/{reps})"
  725. else:
  726. tail = ""
  727. regex = f"^{''.join(regex_parts)}{tail}$"
  728. self._regex = re.compile(regex)
  729. def match(
  730. self, path: str, method: t.Optional[str] = None
  731. ) -> t.Optional[t.MutableMapping[str, t.Any]]:
  732. """Check if the rule matches a given path. Path is a string in the
  733. form ``"subdomain|/path"`` and is assembled by the map. If
  734. the map is doing host matching the subdomain part will be the host
  735. instead.
  736. If the rule matches a dict with the converted values is returned,
  737. otherwise the return value is `None`.
  738. :internal:
  739. """
  740. if not self.build_only:
  741. require_redirect = False
  742. m = self._regex.search(path)
  743. if m is not None:
  744. groups = m.groupdict()
  745. # we have a folder like part of the url without a trailing
  746. # slash and strict slashes enabled. raise an exception that
  747. # tells the map to redirect to the same url but with a
  748. # trailing slash
  749. if (
  750. self.strict_slashes
  751. and not self.is_leaf
  752. and not groups.pop("__suffix__")
  753. and (
  754. method is None or self.methods is None or method in self.methods
  755. )
  756. ):
  757. path += "/"
  758. require_redirect = True
  759. # if we are not in strict slashes mode we have to remove
  760. # a __suffix__
  761. elif not self.strict_slashes:
  762. del groups["__suffix__"]
  763. result = {}
  764. for name, value in groups.items():
  765. try:
  766. value = self._converters[name].to_python(value)
  767. except ValidationError:
  768. return None
  769. result[str(name)] = value
  770. if self.defaults:
  771. result.update(self.defaults)
  772. if self.merge_slashes:
  773. new_path = "|".join(self.build(result, False)) # type: ignore
  774. if path.endswith("/") and not new_path.endswith("/"):
  775. new_path += "/"
  776. if new_path.count("/") < path.count("/"):
  777. # The URL will be encoded when MapAdapter.match
  778. # handles the RequestPath raised below. Decode
  779. # the URL here to avoid a double encoding.
  780. path = url_unquote(new_path)
  781. require_redirect = True
  782. if require_redirect:
  783. path = path.split("|", 1)[1]
  784. raise RequestPath(path)
  785. if self.alias and self.map.redirect_defaults:
  786. raise RequestAliasRedirect(result)
  787. return result
  788. return None
  789. @staticmethod
  790. def _get_func_code(code: CodeType, name: str) -> t.Callable[..., t.Tuple[str, str]]:
  791. globs: t.Dict[str, t.Any] = {}
  792. locs: t.Dict[str, t.Any] = {}
  793. exec(code, globs, locs)
  794. return locs[name] # type: ignore
  795. def _compile_builder(
  796. self, append_unknown: bool = True
  797. ) -> t.Callable[..., t.Tuple[str, str]]:
  798. defaults = self.defaults or {}
  799. dom_ops: t.List[t.Tuple[bool, str]] = []
  800. url_ops: t.List[t.Tuple[bool, str]] = []
  801. opl = dom_ops
  802. for is_dynamic, data in self._trace:
  803. if data == "|" and opl is dom_ops:
  804. opl = url_ops
  805. continue
  806. # this seems like a silly case to ever come up but:
  807. # if a default is given for a value that appears in the rule,
  808. # resolve it to a constant ahead of time
  809. if is_dynamic and data in defaults:
  810. data = self._converters[data].to_url(defaults[data])
  811. opl.append((False, data))
  812. elif not is_dynamic:
  813. opl.append(
  814. (False, url_quote(_to_bytes(data, self.map.charset), safe="/:|+"))
  815. )
  816. else:
  817. opl.append((True, data))
  818. def _convert(elem: str) -> ast.stmt:
  819. ret = _prefix_names(_CALL_CONVERTER_CODE_FMT.format(elem=elem))
  820. ret.args = [ast.Name(str(elem), ast.Load())] # type: ignore # str for py2
  821. return ret
  822. def _parts(ops: t.List[t.Tuple[bool, str]]) -> t.List[ast.AST]:
  823. parts = [
  824. _convert(elem) if is_dynamic else ast.Str(s=elem)
  825. for is_dynamic, elem in ops
  826. ]
  827. parts = parts or [ast.Str("")]
  828. # constant fold
  829. ret = [parts[0]]
  830. for p in parts[1:]:
  831. if isinstance(p, ast.Str) and isinstance(ret[-1], ast.Str):
  832. ret[-1] = ast.Str(ret[-1].s + p.s)
  833. else:
  834. ret.append(p)
  835. return ret
  836. dom_parts = _parts(dom_ops)
  837. url_parts = _parts(url_ops)
  838. if not append_unknown:
  839. body = []
  840. else:
  841. body = [_IF_KWARGS_URL_ENCODE_AST]
  842. url_parts.extend(_URL_ENCODE_AST_NAMES)
  843. def _join(parts: t.List[ast.AST]) -> ast.AST:
  844. if len(parts) == 1: # shortcut
  845. return parts[0]
  846. return ast.JoinedStr(parts)
  847. body.append(
  848. ast.Return(ast.Tuple([_join(dom_parts), _join(url_parts)], ast.Load()))
  849. )
  850. pargs = [
  851. elem
  852. for is_dynamic, elem in dom_ops + url_ops
  853. if is_dynamic and elem not in defaults
  854. ]
  855. kargs = [str(k) for k in defaults]
  856. func_ast: ast.FunctionDef = _prefix_names("def _(): pass") # type: ignore
  857. func_ast.name = f"<builder:{self.rule!r}>"
  858. func_ast.args.args.append(ast.arg(".self", None))
  859. for arg in pargs + kargs:
  860. func_ast.args.args.append(ast.arg(arg, None))
  861. func_ast.args.kwarg = ast.arg(".kwargs", None)
  862. for _ in kargs:
  863. func_ast.args.defaults.append(ast.Str(""))
  864. func_ast.body = body
  865. # use `ast.parse` instead of `ast.Module` for better portability
  866. # Python 3.8 changes the signature of `ast.Module`
  867. module = ast.parse("")
  868. module.body = [func_ast]
  869. # mark everything as on line 1, offset 0
  870. # less error-prone than `ast.fix_missing_locations`
  871. # bad line numbers cause an assert to fail in debug builds
  872. for node in ast.walk(module):
  873. if "lineno" in node._attributes:
  874. node.lineno = 1
  875. if "col_offset" in node._attributes:
  876. node.col_offset = 0
  877. code = compile(module, "<werkzeug routing>", "exec")
  878. return self._get_func_code(code, func_ast.name)
  879. def build(
  880. self, values: t.Mapping[str, t.Any], append_unknown: bool = True
  881. ) -> t.Optional[t.Tuple[str, str]]:
  882. """Assembles the relative url for that rule and the subdomain.
  883. If building doesn't work for some reasons `None` is returned.
  884. :internal:
  885. """
  886. try:
  887. if append_unknown:
  888. return self._build_unknown(**values)
  889. else:
  890. return self._build(**values)
  891. except ValidationError:
  892. return None
  893. def provides_defaults_for(self, rule: "Rule") -> bool:
  894. """Check if this rule has defaults for a given rule.
  895. :internal:
  896. """
  897. return bool(
  898. not self.build_only
  899. and self.defaults
  900. and self.endpoint == rule.endpoint
  901. and self != rule
  902. and self.arguments == rule.arguments
  903. )
  904. def suitable_for(
  905. self, values: t.Mapping[str, t.Any], method: t.Optional[str] = None
  906. ) -> bool:
  907. """Check if the dict of values has enough data for url generation.
  908. :internal:
  909. """
  910. # if a method was given explicitly and that method is not supported
  911. # by this rule, this rule is not suitable.
  912. if (
  913. method is not None
  914. and self.methods is not None
  915. and method not in self.methods
  916. ):
  917. return False
  918. defaults = self.defaults or ()
  919. # all arguments required must be either in the defaults dict or
  920. # the value dictionary otherwise it's not suitable
  921. for key in self.arguments:
  922. if key not in defaults and key not in values:
  923. return False
  924. # in case defaults are given we ensure that either the value was
  925. # skipped or the value is the same as the default value.
  926. if defaults:
  927. for key, value in defaults.items():
  928. if key in values and value != values[key]:
  929. return False
  930. return True
  931. def match_compare_key(
  932. self,
  933. ) -> t.Tuple[bool, int, t.Iterable[t.Tuple[int, int]], int, t.Iterable[int]]:
  934. """The match compare key for sorting.
  935. Current implementation:
  936. 1. rules without any arguments come first for performance
  937. reasons only as we expect them to match faster and some
  938. common ones usually don't have any arguments (index pages etc.)
  939. 2. rules with more static parts come first so the second argument
  940. is the negative length of the number of the static weights.
  941. 3. we order by static weights, which is a combination of index
  942. and length
  943. 4. The more complex rules come first so the next argument is the
  944. negative length of the number of argument weights.
  945. 5. lastly we order by the actual argument weights.
  946. :internal:
  947. """
  948. return (
  949. bool(self.arguments),
  950. -len(self._static_weights),
  951. self._static_weights,
  952. -len(self._argument_weights),
  953. self._argument_weights,
  954. )
  955. def build_compare_key(self) -> t.Tuple[int, int, int]:
  956. """The build compare key for sorting.
  957. :internal:
  958. """
  959. return (1 if self.alias else 0, -len(self.arguments), -len(self.defaults or ()))
  960. def __eq__(self, other: object) -> bool:
  961. return isinstance(other, type(self)) and self._trace == other._trace
  962. __hash__ = None # type: ignore
  963. def __str__(self) -> str:
  964. return self.rule
  965. def __repr__(self) -> str:
  966. if self.map is None:
  967. return f"<{type(self).__name__} (unbound)>"
  968. parts = []
  969. for is_dynamic, data in self._trace:
  970. if is_dynamic:
  971. parts.append(f"<{data}>")
  972. else:
  973. parts.append(data)
  974. parts = "".join(parts).lstrip("|")
  975. methods = f" ({', '.join(self.methods)})" if self.methods is not None else ""
  976. return f"<{type(self).__name__} {parts!r}{methods} -> {self.endpoint}>"
  977. class BaseConverter:
  978. """Base class for all converters."""
  979. regex = "[^/]+"
  980. weight = 100
  981. def __init__(self, map: "Map", *args: t.Any, **kwargs: t.Any) -> None:
  982. self.map = map
  983. def to_python(self, value: str) -> t.Any:
  984. return value
  985. def to_url(self, value: t.Any) -> str:
  986. if isinstance(value, (bytes, bytearray)):
  987. return _fast_url_quote(value)
  988. return _fast_url_quote(str(value).encode(self.map.charset))
  989. class UnicodeConverter(BaseConverter):
  990. """This converter is the default converter and accepts any string but
  991. only one path segment. Thus the string can not include a slash.
  992. This is the default validator.
  993. Example::
  994. Rule('/pages/<page>'),
  995. Rule('/<string(length=2):lang_code>')
  996. :param map: the :class:`Map`.
  997. :param minlength: the minimum length of the string. Must be greater
  998. or equal 1.
  999. :param maxlength: the maximum length of the string.
  1000. :param length: the exact length of the string.
  1001. """
  1002. def __init__(
  1003. self,
  1004. map: "Map",
  1005. minlength: int = 1,
  1006. maxlength: t.Optional[int] = None,
  1007. length: t.Optional[int] = None,
  1008. ) -> None:
  1009. super().__init__(map)
  1010. if length is not None:
  1011. length_regex = f"{{{int(length)}}}"
  1012. else:
  1013. if maxlength is None:
  1014. maxlength_value = ""
  1015. else:
  1016. maxlength_value = str(int(maxlength))
  1017. length_regex = f"{{{int(minlength)},{maxlength_value}}}"
  1018. self.regex = f"[^/]{length_regex}"
  1019. class AnyConverter(BaseConverter):
  1020. """Matches one of the items provided. Items can either be Python
  1021. identifiers or strings::
  1022. Rule('/<any(about, help, imprint, class, "foo,bar"):page_name>')
  1023. :param map: the :class:`Map`.
  1024. :param items: this function accepts the possible items as positional
  1025. arguments.
  1026. """
  1027. def __init__(self, map: "Map", *items: str) -> None:
  1028. super().__init__(map)
  1029. self.regex = f"(?:{'|'.join([re.escape(x) for x in items])})"
  1030. class PathConverter(BaseConverter):
  1031. """Like the default :class:`UnicodeConverter`, but it also matches
  1032. slashes. This is useful for wikis and similar applications::
  1033. Rule('/<path:wikipage>')
  1034. Rule('/<path:wikipage>/edit')
  1035. :param map: the :class:`Map`.
  1036. """
  1037. regex = "[^/].*?"
  1038. weight = 200
  1039. class NumberConverter(BaseConverter):
  1040. """Baseclass for `IntegerConverter` and `FloatConverter`.
  1041. :internal:
  1042. """
  1043. weight = 50
  1044. num_convert: t.Callable = int
  1045. def __init__(
  1046. self,
  1047. map: "Map",
  1048. fixed_digits: int = 0,
  1049. min: t.Optional[int] = None,
  1050. max: t.Optional[int] = None,
  1051. signed: bool = False,
  1052. ) -> None:
  1053. if signed:
  1054. self.regex = self.signed_regex
  1055. super().__init__(map)
  1056. self.fixed_digits = fixed_digits
  1057. self.min = min
  1058. self.max = max
  1059. self.signed = signed
  1060. def to_python(self, value: str) -> t.Any:
  1061. if self.fixed_digits and len(value) != self.fixed_digits:
  1062. raise ValidationError()
  1063. value = self.num_convert(value)
  1064. if (self.min is not None and value < self.min) or (
  1065. self.max is not None and value > self.max
  1066. ):
  1067. raise ValidationError()
  1068. return value
  1069. def to_url(self, value: t.Any) -> str:
  1070. value = str(self.num_convert(value))
  1071. if self.fixed_digits:
  1072. value = value.zfill(self.fixed_digits)
  1073. return value
  1074. @property
  1075. def signed_regex(self) -> str:
  1076. return f"-?{self.regex}"
  1077. class IntegerConverter(NumberConverter):
  1078. """This converter only accepts integer values::
  1079. Rule("/page/<int:page>")
  1080. By default it only accepts unsigned, positive values. The ``signed``
  1081. parameter will enable signed, negative values. ::
  1082. Rule("/page/<int(signed=True):page>")
  1083. :param map: The :class:`Map`.
  1084. :param fixed_digits: The number of fixed digits in the URL. If you
  1085. set this to ``4`` for example, the rule will only match if the
  1086. URL looks like ``/0001/``. The default is variable length.
  1087. :param min: The minimal value.
  1088. :param max: The maximal value.
  1089. :param signed: Allow signed (negative) values.
  1090. .. versionadded:: 0.15
  1091. The ``signed`` parameter.
  1092. """
  1093. regex = r"\d+"
  1094. class FloatConverter(NumberConverter):
  1095. """This converter only accepts floating point values::
  1096. Rule("/probability/<float:probability>")
  1097. By default it only accepts unsigned, positive values. The ``signed``
  1098. parameter will enable signed, negative values. ::
  1099. Rule("/offset/<float(signed=True):offset>")
  1100. :param map: The :class:`Map`.
  1101. :param min: The minimal value.
  1102. :param max: The maximal value.
  1103. :param signed: Allow signed (negative) values.
  1104. .. versionadded:: 0.15
  1105. The ``signed`` parameter.
  1106. """
  1107. regex = r"\d+\.\d+"
  1108. num_convert = float
  1109. def __init__(
  1110. self,
  1111. map: "Map",
  1112. min: t.Optional[float] = None,
  1113. max: t.Optional[float] = None,
  1114. signed: bool = False,
  1115. ) -> None:
  1116. super().__init__(map, min=min, max=max, signed=signed) # type: ignore
  1117. class UUIDConverter(BaseConverter):
  1118. """This converter only accepts UUID strings::
  1119. Rule('/object/<uuid:identifier>')
  1120. .. versionadded:: 0.10
  1121. :param map: the :class:`Map`.
  1122. """
  1123. regex = (
  1124. r"[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-"
  1125. r"[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}"
  1126. )
  1127. def to_python(self, value: str) -> uuid.UUID:
  1128. return uuid.UUID(value)
  1129. def to_url(self, value: uuid.UUID) -> str:
  1130. return str(value)
  1131. #: the default converter mapping for the map.
  1132. DEFAULT_CONVERTERS: t.Mapping[str, t.Type[BaseConverter]] = {
  1133. "default": UnicodeConverter,
  1134. "string": UnicodeConverter,
  1135. "any": AnyConverter,
  1136. "path": PathConverter,
  1137. "int": IntegerConverter,
  1138. "float": FloatConverter,
  1139. "uuid": UUIDConverter,
  1140. }
  1141. class Map:
  1142. """The map class stores all the URL rules and some configuration
  1143. parameters. Some of the configuration values are only stored on the
  1144. `Map` instance since those affect all rules, others are just defaults
  1145. and can be overridden for each rule. Note that you have to specify all
  1146. arguments besides the `rules` as keyword arguments!
  1147. :param rules: sequence of url rules for this map.
  1148. :param default_subdomain: The default subdomain for rules without a
  1149. subdomain defined.
  1150. :param charset: charset of the url. defaults to ``"utf-8"``
  1151. :param strict_slashes: If a rule ends with a slash but the matched
  1152. URL does not, redirect to the URL with a trailing slash.
  1153. :param merge_slashes: Merge consecutive slashes when matching or
  1154. building URLs. Matches will redirect to the normalized URL.
  1155. Slashes in variable parts are not merged.
  1156. :param redirect_defaults: This will redirect to the default rule if it
  1157. wasn't visited that way. This helps creating
  1158. unique URLs.
  1159. :param converters: A dict of converters that adds additional converters
  1160. to the list of converters. If you redefine one
  1161. converter this will override the original one.
  1162. :param sort_parameters: If set to `True` the url parameters are sorted.
  1163. See `url_encode` for more details.
  1164. :param sort_key: The sort key function for `url_encode`.
  1165. :param encoding_errors: the error method to use for decoding
  1166. :param host_matching: if set to `True` it enables the host matching
  1167. feature and disables the subdomain one. If
  1168. enabled the `host` parameter to rules is used
  1169. instead of the `subdomain` one.
  1170. .. versionchanged:: 1.0
  1171. If ``url_scheme`` is ``ws`` or ``wss``, only WebSocket rules
  1172. will match.
  1173. .. versionchanged:: 1.0
  1174. Added ``merge_slashes``.
  1175. .. versionchanged:: 0.7
  1176. Added ``encoding_errors`` and ``host_matching``.
  1177. .. versionchanged:: 0.5
  1178. Added ``sort_parameters`` and ``sort_key``.
  1179. """
  1180. #: A dict of default converters to be used.
  1181. default_converters = ImmutableDict(DEFAULT_CONVERTERS)
  1182. #: The type of lock to use when updating.
  1183. #:
  1184. #: .. versionadded:: 1.0
  1185. lock_class = Lock
  1186. def __init__(
  1187. self,
  1188. rules: t.Optional[t.Iterable[RuleFactory]] = None,
  1189. default_subdomain: str = "",
  1190. charset: str = "utf-8",
  1191. strict_slashes: bool = True,
  1192. merge_slashes: bool = True,
  1193. redirect_defaults: bool = True,
  1194. converters: t.Optional[t.Mapping[str, t.Type[BaseConverter]]] = None,
  1195. sort_parameters: bool = False,
  1196. sort_key: t.Optional[t.Callable[[t.Any], t.Any]] = None,
  1197. encoding_errors: str = "replace",
  1198. host_matching: bool = False,
  1199. ) -> None:
  1200. self._rules: t.List[Rule] = []
  1201. self._rules_by_endpoint: t.Dict[str, t.List[Rule]] = {}
  1202. self._remap = True
  1203. self._remap_lock = self.lock_class()
  1204. self.default_subdomain = default_subdomain
  1205. self.charset = charset
  1206. self.encoding_errors = encoding_errors
  1207. self.strict_slashes = strict_slashes
  1208. self.merge_slashes = merge_slashes
  1209. self.redirect_defaults = redirect_defaults
  1210. self.host_matching = host_matching
  1211. self.converters = self.default_converters.copy()
  1212. if converters:
  1213. self.converters.update(converters)
  1214. self.sort_parameters = sort_parameters
  1215. self.sort_key = sort_key
  1216. for rulefactory in rules or ():
  1217. self.add(rulefactory)
  1218. def is_endpoint_expecting(self, endpoint: str, *arguments: str) -> bool:
  1219. """Iterate over all rules and check if the endpoint expects
  1220. the arguments provided. This is for example useful if you have
  1221. some URLs that expect a language code and others that do not and
  1222. you want to wrap the builder a bit so that the current language
  1223. code is automatically added if not provided but endpoints expect
  1224. it.
  1225. :param endpoint: the endpoint to check.
  1226. :param arguments: this function accepts one or more arguments
  1227. as positional arguments. Each one of them is
  1228. checked.
  1229. """
  1230. self.update()
  1231. arguments = set(arguments)
  1232. for rule in self._rules_by_endpoint[endpoint]:
  1233. if arguments.issubset(rule.arguments):
  1234. return True
  1235. return False
  1236. def iter_rules(self, endpoint: t.Optional[str] = None) -> t.Iterator[Rule]:
  1237. """Iterate over all rules or the rules of an endpoint.
  1238. :param endpoint: if provided only the rules for that endpoint
  1239. are returned.
  1240. :return: an iterator
  1241. """
  1242. self.update()
  1243. if endpoint is not None:
  1244. return iter(self._rules_by_endpoint[endpoint])
  1245. return iter(self._rules)
  1246. def add(self, rulefactory: RuleFactory) -> None:
  1247. """Add a new rule or factory to the map and bind it. Requires that the
  1248. rule is not bound to another map.
  1249. :param rulefactory: a :class:`Rule` or :class:`RuleFactory`
  1250. """
  1251. for rule in rulefactory.get_rules(self):
  1252. rule.bind(self)
  1253. self._rules.append(rule)
  1254. self._rules_by_endpoint.setdefault(rule.endpoint, []).append(rule)
  1255. self._remap = True
  1256. def bind(
  1257. self,
  1258. server_name: str,
  1259. script_name: t.Optional[str] = None,
  1260. subdomain: t.Optional[str] = None,
  1261. url_scheme: str = "http",
  1262. default_method: str = "GET",
  1263. path_info: t.Optional[str] = None,
  1264. query_args: t.Optional[t.Union[t.Mapping[str, t.Any], str]] = None,
  1265. ) -> "MapAdapter":
  1266. """Return a new :class:`MapAdapter` with the details specified to the
  1267. call. Note that `script_name` will default to ``'/'`` if not further
  1268. specified or `None`. The `server_name` at least is a requirement
  1269. because the HTTP RFC requires absolute URLs for redirects and so all
  1270. redirect exceptions raised by Werkzeug will contain the full canonical
  1271. URL.
  1272. If no path_info is passed to :meth:`match` it will use the default path
  1273. info passed to bind. While this doesn't really make sense for
  1274. manual bind calls, it's useful if you bind a map to a WSGI
  1275. environment which already contains the path info.
  1276. `subdomain` will default to the `default_subdomain` for this map if
  1277. no defined. If there is no `default_subdomain` you cannot use the
  1278. subdomain feature.
  1279. .. versionchanged:: 1.0
  1280. If ``url_scheme`` is ``ws`` or ``wss``, only WebSocket rules
  1281. will match.
  1282. .. versionchanged:: 0.15
  1283. ``path_info`` defaults to ``'/'`` if ``None``.
  1284. .. versionchanged:: 0.8
  1285. ``query_args`` can be a string.
  1286. .. versionchanged:: 0.7
  1287. Added ``query_args``.
  1288. """
  1289. server_name = server_name.lower()
  1290. if self.host_matching:
  1291. if subdomain is not None:
  1292. raise RuntimeError("host matching enabled and a subdomain was provided")
  1293. elif subdomain is None:
  1294. subdomain = self.default_subdomain
  1295. if script_name is None:
  1296. script_name = "/"
  1297. if path_info is None:
  1298. path_info = "/"
  1299. try:
  1300. server_name = _encode_idna(server_name) # type: ignore
  1301. except UnicodeError as e:
  1302. raise BadHost() from e
  1303. return MapAdapter(
  1304. self,
  1305. server_name,
  1306. script_name,
  1307. subdomain,
  1308. url_scheme,
  1309. path_info,
  1310. default_method,
  1311. query_args,
  1312. )
  1313. def bind_to_environ(
  1314. self,
  1315. environ: t.Union["WSGIEnvironment", "Request"],
  1316. server_name: t.Optional[str] = None,
  1317. subdomain: t.Optional[str] = None,
  1318. ) -> "MapAdapter":
  1319. """Like :meth:`bind` but you can pass it an WSGI environment and it
  1320. will fetch the information from that dictionary. Note that because of
  1321. limitations in the protocol there is no way to get the current
  1322. subdomain and real `server_name` from the environment. If you don't
  1323. provide it, Werkzeug will use `SERVER_NAME` and `SERVER_PORT` (or
  1324. `HTTP_HOST` if provided) as used `server_name` with disabled subdomain
  1325. feature.
  1326. If `subdomain` is `None` but an environment and a server name is
  1327. provided it will calculate the current subdomain automatically.
  1328. Example: `server_name` is ``'example.com'`` and the `SERVER_NAME`
  1329. in the wsgi `environ` is ``'staging.dev.example.com'`` the calculated
  1330. subdomain will be ``'staging.dev'``.
  1331. If the object passed as environ has an environ attribute, the value of
  1332. this attribute is used instead. This allows you to pass request
  1333. objects. Additionally `PATH_INFO` added as a default of the
  1334. :class:`MapAdapter` so that you don't have to pass the path info to
  1335. the match method.
  1336. .. versionchanged:: 1.0.0
  1337. If the passed server name specifies port 443, it will match
  1338. if the incoming scheme is ``https`` without a port.
  1339. .. versionchanged:: 1.0.0
  1340. A warning is shown when the passed server name does not
  1341. match the incoming WSGI server name.
  1342. .. versionchanged:: 0.8
  1343. This will no longer raise a ValueError when an unexpected server
  1344. name was passed.
  1345. .. versionchanged:: 0.5
  1346. previously this method accepted a bogus `calculate_subdomain`
  1347. parameter that did not have any effect. It was removed because
  1348. of that.
  1349. :param environ: a WSGI environment.
  1350. :param server_name: an optional server name hint (see above).
  1351. :param subdomain: optionally the current subdomain (see above).
  1352. """
  1353. env = _get_environ(environ)
  1354. wsgi_server_name = get_host(env).lower()
  1355. scheme = env["wsgi.url_scheme"]
  1356. upgrade = any(
  1357. v.strip() == "upgrade"
  1358. for v in env.get("HTTP_CONNECTION", "").lower().split(",")
  1359. )
  1360. if upgrade and env.get("HTTP_UPGRADE", "").lower() == "websocket":
  1361. scheme = "wss" if scheme == "https" else "ws"
  1362. if server_name is None:
  1363. server_name = wsgi_server_name
  1364. else:
  1365. server_name = server_name.lower()
  1366. # strip standard port to match get_host()
  1367. if scheme in {"http", "ws"} and server_name.endswith(":80"):
  1368. server_name = server_name[:-3]
  1369. elif scheme in {"https", "wss"} and server_name.endswith(":443"):
  1370. server_name = server_name[:-4]
  1371. if subdomain is None and not self.host_matching:
  1372. cur_server_name = wsgi_server_name.split(".")
  1373. real_server_name = server_name.split(".")
  1374. offset = -len(real_server_name)
  1375. if cur_server_name[offset:] != real_server_name:
  1376. # This can happen even with valid configs if the server was
  1377. # accessed directly by IP address under some situations.
  1378. # Instead of raising an exception like in Werkzeug 0.7 or
  1379. # earlier we go by an invalid subdomain which will result
  1380. # in a 404 error on matching.
  1381. warnings.warn(
  1382. f"Current server name {wsgi_server_name!r} doesn't match configured"
  1383. f" server name {server_name!r}",
  1384. stacklevel=2,
  1385. )
  1386. subdomain = "<invalid>"
  1387. else:
  1388. subdomain = ".".join(filter(None, cur_server_name[:offset]))
  1389. def _get_wsgi_string(name: str) -> t.Optional[str]:
  1390. val = env.get(name)
  1391. if val is not None:
  1392. return _wsgi_decoding_dance(val, self.charset)
  1393. return None
  1394. script_name = _get_wsgi_string("SCRIPT_NAME")
  1395. path_info = _get_wsgi_string("PATH_INFO")
  1396. query_args = _get_wsgi_string("QUERY_STRING")
  1397. return Map.bind(
  1398. self,
  1399. server_name,
  1400. script_name,
  1401. subdomain,
  1402. scheme,
  1403. env["REQUEST_METHOD"],
  1404. path_info,
  1405. query_args=query_args,
  1406. )
  1407. def update(self) -> None:
  1408. """Called before matching and building to keep the compiled rules
  1409. in the correct order after things changed.
  1410. """
  1411. if not self._remap:
  1412. return
  1413. with self._remap_lock:
  1414. if not self._remap:
  1415. return
  1416. self._rules.sort(key=lambda x: x.match_compare_key())
  1417. for rules in self._rules_by_endpoint.values():
  1418. rules.sort(key=lambda x: x.build_compare_key())
  1419. self._remap = False
  1420. def __repr__(self) -> str:
  1421. rules = self.iter_rules()
  1422. return f"{type(self).__name__}({pformat(list(rules))})"
  1423. class MapAdapter:
  1424. """Returned by :meth:`Map.bind` or :meth:`Map.bind_to_environ` and does
  1425. the URL matching and building based on runtime information.
  1426. """
  1427. def __init__(
  1428. self,
  1429. map: Map,
  1430. server_name: str,
  1431. script_name: str,
  1432. subdomain: t.Optional[str],
  1433. url_scheme: str,
  1434. path_info: str,
  1435. default_method: str,
  1436. query_args: t.Optional[t.Union[t.Mapping[str, t.Any], str]] = None,
  1437. ):
  1438. self.map = map
  1439. self.server_name = _to_str(server_name)
  1440. script_name = _to_str(script_name)
  1441. if not script_name.endswith("/"):
  1442. script_name += "/"
  1443. self.script_name = script_name
  1444. self.subdomain = _to_str(subdomain)
  1445. self.url_scheme = _to_str(url_scheme)
  1446. self.path_info = _to_str(path_info)
  1447. self.default_method = _to_str(default_method)
  1448. self.query_args = query_args
  1449. self.websocket = self.url_scheme in {"ws", "wss"}
  1450. def dispatch(
  1451. self,
  1452. view_func: t.Callable[[str, t.Mapping[str, t.Any]], "WSGIApplication"],
  1453. path_info: t.Optional[str] = None,
  1454. method: t.Optional[str] = None,
  1455. catch_http_exceptions: bool = False,
  1456. ) -> "WSGIApplication":
  1457. """Does the complete dispatching process. `view_func` is called with
  1458. the endpoint and a dict with the values for the view. It should
  1459. look up the view function, call it, and return a response object
  1460. or WSGI application. http exceptions are not caught by default
  1461. so that applications can display nicer error messages by just
  1462. catching them by hand. If you want to stick with the default
  1463. error messages you can pass it ``catch_http_exceptions=True`` and
  1464. it will catch the http exceptions.
  1465. Here a small example for the dispatch usage::
  1466. from werkzeug.wrappers import Request, Response
  1467. from werkzeug.wsgi import responder
  1468. from werkzeug.routing import Map, Rule
  1469. def on_index(request):
  1470. return Response('Hello from the index')
  1471. url_map = Map([Rule('/', endpoint='index')])
  1472. views = {'index': on_index}
  1473. @responder
  1474. def application(environ, start_response):
  1475. request = Request(environ)
  1476. urls = url_map.bind_to_environ(environ)
  1477. return urls.dispatch(lambda e, v: views[e](request, **v),
  1478. catch_http_exceptions=True)
  1479. Keep in mind that this method might return exception objects, too, so
  1480. use :class:`Response.force_type` to get a response object.
  1481. :param view_func: a function that is called with the endpoint as
  1482. first argument and the value dict as second. Has
  1483. to dispatch to the actual view function with this
  1484. information. (see above)
  1485. :param path_info: the path info to use for matching. Overrides the
  1486. path info specified on binding.
  1487. :param method: the HTTP method used for matching. Overrides the
  1488. method specified on binding.
  1489. :param catch_http_exceptions: set to `True` to catch any of the
  1490. werkzeug :class:`HTTPException`\\s.
  1491. """
  1492. try:
  1493. try:
  1494. endpoint, args = self.match(path_info, method)
  1495. except RequestRedirect as e:
  1496. return e
  1497. return view_func(endpoint, args)
  1498. except HTTPException as e:
  1499. if catch_http_exceptions:
  1500. return e
  1501. raise
  1502. @typing.overload
  1503. def match( # type: ignore
  1504. self,
  1505. path_info: t.Optional[str] = None,
  1506. method: t.Optional[str] = None,
  1507. return_rule: "te.Literal[False]" = False,
  1508. query_args: t.Optional[t.Union[t.Mapping[str, t.Any], str]] = None,
  1509. websocket: t.Optional[bool] = None,
  1510. ) -> t.Tuple[str, t.Mapping[str, t.Any]]:
  1511. ...
  1512. @typing.overload
  1513. def match(
  1514. self,
  1515. path_info: t.Optional[str] = None,
  1516. method: t.Optional[str] = None,
  1517. return_rule: "te.Literal[True]" = True,
  1518. query_args: t.Optional[t.Union[t.Mapping[str, t.Any], str]] = None,
  1519. websocket: t.Optional[bool] = None,
  1520. ) -> t.Tuple[Rule, t.Mapping[str, t.Any]]:
  1521. ...
  1522. def match(
  1523. self,
  1524. path_info: t.Optional[str] = None,
  1525. method: t.Optional[str] = None,
  1526. return_rule: bool = False,
  1527. query_args: t.Optional[t.Union[t.Mapping[str, t.Any], str]] = None,
  1528. websocket: t.Optional[bool] = None,
  1529. ) -> t.Tuple[t.Union[str, Rule], t.Mapping[str, t.Any]]:
  1530. """The usage is simple: you just pass the match method the current
  1531. path info as well as the method (which defaults to `GET`). The
  1532. following things can then happen:
  1533. - you receive a `NotFound` exception that indicates that no URL is
  1534. matching. A `NotFound` exception is also a WSGI application you
  1535. can call to get a default page not found page (happens to be the
  1536. same object as `werkzeug.exceptions.NotFound`)
  1537. - you receive a `MethodNotAllowed` exception that indicates that there
  1538. is a match for this URL but not for the current request method.
  1539. This is useful for RESTful applications.
  1540. - you receive a `RequestRedirect` exception with a `new_url`
  1541. attribute. This exception is used to notify you about a request
  1542. Werkzeug requests from your WSGI application. This is for example the
  1543. case if you request ``/foo`` although the correct URL is ``/foo/``
  1544. You can use the `RequestRedirect` instance as response-like object
  1545. similar to all other subclasses of `HTTPException`.
  1546. - you receive a ``WebsocketMismatch`` exception if the only
  1547. match is a WebSocket rule but the bind is an HTTP request, or
  1548. if the match is an HTTP rule but the bind is a WebSocket
  1549. request.
  1550. - you get a tuple in the form ``(endpoint, arguments)`` if there is
  1551. a match (unless `return_rule` is True, in which case you get a tuple
  1552. in the form ``(rule, arguments)``)
  1553. If the path info is not passed to the match method the default path
  1554. info of the map is used (defaults to the root URL if not defined
  1555. explicitly).
  1556. All of the exceptions raised are subclasses of `HTTPException` so they
  1557. can be used as WSGI responses. They will all render generic error or
  1558. redirect pages.
  1559. Here is a small example for matching:
  1560. >>> m = Map([
  1561. ... Rule('/', endpoint='index'),
  1562. ... Rule('/downloads/', endpoint='downloads/index'),
  1563. ... Rule('/downloads/<int:id>', endpoint='downloads/show')
  1564. ... ])
  1565. >>> urls = m.bind("example.com", "/")
  1566. >>> urls.match("/", "GET")
  1567. ('index', {})
  1568. >>> urls.match("/downloads/42")
  1569. ('downloads/show', {'id': 42})
  1570. And here is what happens on redirect and missing URLs:
  1571. >>> urls.match("/downloads")
  1572. Traceback (most recent call last):
  1573. ...
  1574. RequestRedirect: http://example.com/downloads/
  1575. >>> urls.match("/missing")
  1576. Traceback (most recent call last):
  1577. ...
  1578. NotFound: 404 Not Found
  1579. :param path_info: the path info to use for matching. Overrides the
  1580. path info specified on binding.
  1581. :param method: the HTTP method used for matching. Overrides the
  1582. method specified on binding.
  1583. :param return_rule: return the rule that matched instead of just the
  1584. endpoint (defaults to `False`).
  1585. :param query_args: optional query arguments that are used for
  1586. automatic redirects as string or dictionary. It's
  1587. currently not possible to use the query arguments
  1588. for URL matching.
  1589. :param websocket: Match WebSocket instead of HTTP requests. A
  1590. websocket request has a ``ws`` or ``wss``
  1591. :attr:`url_scheme`. This overrides that detection.
  1592. .. versionadded:: 1.0
  1593. Added ``websocket``.
  1594. .. versionchanged:: 0.8
  1595. ``query_args`` can be a string.
  1596. .. versionadded:: 0.7
  1597. Added ``query_args``.
  1598. .. versionadded:: 0.6
  1599. Added ``return_rule``.
  1600. """
  1601. self.map.update()
  1602. if path_info is None:
  1603. path_info = self.path_info
  1604. else:
  1605. path_info = _to_str(path_info, self.map.charset)
  1606. if query_args is None:
  1607. query_args = self.query_args or {}
  1608. method = (method or self.default_method).upper()
  1609. if websocket is None:
  1610. websocket = self.websocket
  1611. require_redirect = False
  1612. domain_part = self.server_name if self.map.host_matching else self.subdomain
  1613. path_part = f"/{path_info.lstrip('/')}" if path_info else ""
  1614. path = f"{domain_part}|{path_part}"
  1615. have_match_for = set()
  1616. websocket_mismatch = False
  1617. for rule in self.map._rules:
  1618. try:
  1619. rv = rule.match(path, method)
  1620. except RequestPath as e:
  1621. raise RequestRedirect(
  1622. self.make_redirect_url(
  1623. url_quote(e.path_info, self.map.charset, safe="/:|+"),
  1624. query_args,
  1625. )
  1626. ) from None
  1627. except RequestAliasRedirect as e:
  1628. raise RequestRedirect(
  1629. self.make_alias_redirect_url(
  1630. path, rule.endpoint, e.matched_values, method, query_args
  1631. )
  1632. ) from None
  1633. if rv is None:
  1634. continue
  1635. if rule.methods is not None and method not in rule.methods:
  1636. have_match_for.update(rule.methods)
  1637. continue
  1638. if rule.websocket != websocket:
  1639. websocket_mismatch = True
  1640. continue
  1641. if self.map.redirect_defaults:
  1642. redirect_url = self.get_default_redirect(rule, method, rv, query_args)
  1643. if redirect_url is not None:
  1644. raise RequestRedirect(redirect_url)
  1645. if rule.redirect_to is not None:
  1646. if isinstance(rule.redirect_to, str):
  1647. def _handle_match(match: t.Match[str]) -> str:
  1648. value = rv[match.group(1)] # type: ignore
  1649. return rule._converters[match.group(1)].to_url(value)
  1650. redirect_url = _simple_rule_re.sub(_handle_match, rule.redirect_to)
  1651. else:
  1652. redirect_url = rule.redirect_to(self, **rv)
  1653. if self.subdomain:
  1654. netloc = f"{self.subdomain}.{self.server_name}"
  1655. else:
  1656. netloc = self.server_name
  1657. raise RequestRedirect(
  1658. url_join(
  1659. f"{self.url_scheme or 'http'}://{netloc}{self.script_name}",
  1660. redirect_url,
  1661. )
  1662. )
  1663. if require_redirect:
  1664. raise RequestRedirect(
  1665. self.make_redirect_url(
  1666. url_quote(path_info, self.map.charset, safe="/:|+"), query_args
  1667. )
  1668. )
  1669. if return_rule:
  1670. return rule, rv
  1671. else:
  1672. return rule.endpoint, rv
  1673. if have_match_for:
  1674. raise MethodNotAllowed(valid_methods=list(have_match_for))
  1675. if websocket_mismatch:
  1676. raise WebsocketMismatch()
  1677. raise NotFound()
  1678. def test(
  1679. self, path_info: t.Optional[str] = None, method: t.Optional[str] = None
  1680. ) -> bool:
  1681. """Test if a rule would match. Works like `match` but returns `True`
  1682. if the URL matches, or `False` if it does not exist.
  1683. :param path_info: the path info to use for matching. Overrides the
  1684. path info specified on binding.
  1685. :param method: the HTTP method used for matching. Overrides the
  1686. method specified on binding.
  1687. """
  1688. try:
  1689. self.match(path_info, method)
  1690. except RequestRedirect:
  1691. pass
  1692. except HTTPException:
  1693. return False
  1694. return True
  1695. def allowed_methods(self, path_info: t.Optional[str] = None) -> t.Iterable[str]:
  1696. """Returns the valid methods that match for a given path.
  1697. .. versionadded:: 0.7
  1698. """
  1699. try:
  1700. self.match(path_info, method="--")
  1701. except MethodNotAllowed as e:
  1702. return e.valid_methods # type: ignore
  1703. except HTTPException:
  1704. pass
  1705. return []
  1706. def get_host(self, domain_part: t.Optional[str]) -> str:
  1707. """Figures out the full host name for the given domain part. The
  1708. domain part is a subdomain in case host matching is disabled or
  1709. a full host name.
  1710. """
  1711. if self.map.host_matching:
  1712. if domain_part is None:
  1713. return self.server_name
  1714. return _to_str(domain_part, "ascii")
  1715. subdomain = domain_part
  1716. if subdomain is None:
  1717. subdomain = self.subdomain
  1718. else:
  1719. subdomain = _to_str(subdomain, "ascii")
  1720. if subdomain:
  1721. return f"{subdomain}.{self.server_name}"
  1722. else:
  1723. return self.server_name
  1724. def get_default_redirect(
  1725. self,
  1726. rule: Rule,
  1727. method: str,
  1728. values: t.MutableMapping[str, t.Any],
  1729. query_args: t.Union[t.Mapping[str, t.Any], str],
  1730. ) -> t.Optional[str]:
  1731. """A helper that returns the URL to redirect to if it finds one.
  1732. This is used for default redirecting only.
  1733. :internal:
  1734. """
  1735. assert self.map.redirect_defaults
  1736. for r in self.map._rules_by_endpoint[rule.endpoint]:
  1737. # every rule that comes after this one, including ourself
  1738. # has a lower priority for the defaults. We order the ones
  1739. # with the highest priority up for building.
  1740. if r is rule:
  1741. break
  1742. if r.provides_defaults_for(rule) and r.suitable_for(values, method):
  1743. values.update(r.defaults) # type: ignore
  1744. domain_part, path = r.build(values) # type: ignore
  1745. return self.make_redirect_url(path, query_args, domain_part=domain_part)
  1746. return None
  1747. def encode_query_args(self, query_args: t.Union[t.Mapping[str, t.Any], str]) -> str:
  1748. if not isinstance(query_args, str):
  1749. return url_encode(query_args, self.map.charset)
  1750. return query_args
  1751. def make_redirect_url(
  1752. self,
  1753. path_info: str,
  1754. query_args: t.Optional[t.Union[t.Mapping[str, t.Any], str]] = None,
  1755. domain_part: t.Optional[str] = None,
  1756. ) -> str:
  1757. """Creates a redirect URL.
  1758. :internal:
  1759. """
  1760. if query_args:
  1761. suffix = f"?{self.encode_query_args(query_args)}"
  1762. else:
  1763. suffix = ""
  1764. scheme = self.url_scheme or "http"
  1765. host = self.get_host(domain_part)
  1766. path = posixpath.join(self.script_name.strip("/"), path_info.lstrip("/"))
  1767. return f"{scheme}://{host}/{path}{suffix}"
  1768. def make_alias_redirect_url(
  1769. self,
  1770. path: str,
  1771. endpoint: str,
  1772. values: t.Mapping[str, t.Any],
  1773. method: str,
  1774. query_args: t.Union[t.Mapping[str, t.Any], str],
  1775. ) -> str:
  1776. """Internally called to make an alias redirect URL."""
  1777. url = self.build(
  1778. endpoint, values, method, append_unknown=False, force_external=True
  1779. )
  1780. if query_args:
  1781. url += f"?{self.encode_query_args(query_args)}"
  1782. assert url != path, "detected invalid alias setting. No canonical URL found"
  1783. return url
  1784. def _partial_build(
  1785. self,
  1786. endpoint: str,
  1787. values: t.Mapping[str, t.Any],
  1788. method: t.Optional[str],
  1789. append_unknown: bool,
  1790. ) -> t.Optional[t.Tuple[str, str, bool]]:
  1791. """Helper for :meth:`build`. Returns subdomain and path for the
  1792. rule that accepts this endpoint, values and method.
  1793. :internal:
  1794. """
  1795. # in case the method is none, try with the default method first
  1796. if method is None:
  1797. rv = self._partial_build(
  1798. endpoint, values, self.default_method, append_unknown
  1799. )
  1800. if rv is not None:
  1801. return rv
  1802. # Default method did not match or a specific method is passed.
  1803. # Check all for first match with matching host. If no matching
  1804. # host is found, go with first result.
  1805. first_match = None
  1806. for rule in self.map._rules_by_endpoint.get(endpoint, ()):
  1807. if rule.suitable_for(values, method):
  1808. build_rv = rule.build(values, append_unknown)
  1809. if build_rv is not None:
  1810. rv = (build_rv[0], build_rv[1], rule.websocket)
  1811. if self.map.host_matching:
  1812. if rv[0] == self.server_name:
  1813. return rv
  1814. elif first_match is None:
  1815. first_match = rv
  1816. else:
  1817. return rv
  1818. return first_match
  1819. def build(
  1820. self,
  1821. endpoint: str,
  1822. values: t.Optional[t.Mapping[str, t.Any]] = None,
  1823. method: t.Optional[str] = None,
  1824. force_external: bool = False,
  1825. append_unknown: bool = True,
  1826. url_scheme: t.Optional[str] = None,
  1827. ) -> str:
  1828. """Building URLs works pretty much the other way round. Instead of
  1829. `match` you call `build` and pass it the endpoint and a dict of
  1830. arguments for the placeholders.
  1831. The `build` function also accepts an argument called `force_external`
  1832. which, if you set it to `True` will force external URLs. Per default
  1833. external URLs (include the server name) will only be used if the
  1834. target URL is on a different subdomain.
  1835. >>> m = Map([
  1836. ... Rule('/', endpoint='index'),
  1837. ... Rule('/downloads/', endpoint='downloads/index'),
  1838. ... Rule('/downloads/<int:id>', endpoint='downloads/show')
  1839. ... ])
  1840. >>> urls = m.bind("example.com", "/")
  1841. >>> urls.build("index", {})
  1842. '/'
  1843. >>> urls.build("downloads/show", {'id': 42})
  1844. '/downloads/42'
  1845. >>> urls.build("downloads/show", {'id': 42}, force_external=True)
  1846. 'http://example.com/downloads/42'
  1847. Because URLs cannot contain non ASCII data you will always get
  1848. bytes back. Non ASCII characters are urlencoded with the
  1849. charset defined on the map instance.
  1850. Additional values are converted to strings and appended to the URL as
  1851. URL querystring parameters:
  1852. >>> urls.build("index", {'q': 'My Searchstring'})
  1853. '/?q=My+Searchstring'
  1854. When processing those additional values, lists are furthermore
  1855. interpreted as multiple values (as per
  1856. :py:class:`werkzeug.datastructures.MultiDict`):
  1857. >>> urls.build("index", {'q': ['a', 'b', 'c']})
  1858. '/?q=a&q=b&q=c'
  1859. Passing a ``MultiDict`` will also add multiple values:
  1860. >>> urls.build("index", MultiDict((('p', 'z'), ('q', 'a'), ('q', 'b'))))
  1861. '/?p=z&q=a&q=b'
  1862. If a rule does not exist when building a `BuildError` exception is
  1863. raised.
  1864. The build method accepts an argument called `method` which allows you
  1865. to specify the method you want to have an URL built for if you have
  1866. different methods for the same endpoint specified.
  1867. :param endpoint: the endpoint of the URL to build.
  1868. :param values: the values for the URL to build. Unhandled values are
  1869. appended to the URL as query parameters.
  1870. :param method: the HTTP method for the rule if there are different
  1871. URLs for different methods on the same endpoint.
  1872. :param force_external: enforce full canonical external URLs. If the URL
  1873. scheme is not provided, this will generate
  1874. a protocol-relative URL.
  1875. :param append_unknown: unknown parameters are appended to the generated
  1876. URL as query string argument. Disable this
  1877. if you want the builder to ignore those.
  1878. :param url_scheme: Scheme to use in place of the bound
  1879. :attr:`url_scheme`.
  1880. .. versionchanged:: 2.0
  1881. Added the ``url_scheme`` parameter.
  1882. .. versionadded:: 0.6
  1883. Added the ``append_unknown`` parameter.
  1884. """
  1885. self.map.update()
  1886. if values:
  1887. temp_values: t.Dict[str, t.Union[t.List[t.Any], t.Any]] = {}
  1888. always_list = isinstance(values, MultiDict)
  1889. key: str
  1890. value: t.Optional[t.Union[t.List[t.Any], t.Any]]
  1891. # For MultiDict, dict.items(values) is like values.lists()
  1892. # without the call or list coercion overhead.
  1893. for key, value in dict.items(values): # type: ignore
  1894. if value is None:
  1895. continue
  1896. if always_list or isinstance(value, (list, tuple)):
  1897. value = [v for v in value if v is not None]
  1898. if not value:
  1899. continue
  1900. if len(value) == 1:
  1901. value = value[0]
  1902. temp_values[key] = value
  1903. values = temp_values
  1904. else:
  1905. values = {}
  1906. rv = self._partial_build(endpoint, values, method, append_unknown)
  1907. if rv is None:
  1908. raise BuildError(endpoint, values, method, self)
  1909. domain_part, path, websocket = rv
  1910. host = self.get_host(domain_part)
  1911. if url_scheme is None:
  1912. url_scheme = self.url_scheme
  1913. # Always build WebSocket routes with the scheme (browsers
  1914. # require full URLs). If bound to a WebSocket, ensure that HTTP
  1915. # routes are built with an HTTP scheme.
  1916. secure = url_scheme in {"https", "wss"}
  1917. if websocket:
  1918. force_external = True
  1919. url_scheme = "wss" if secure else "ws"
  1920. elif url_scheme:
  1921. url_scheme = "https" if secure else "http"
  1922. # shortcut this.
  1923. if not force_external and (
  1924. (self.map.host_matching and host == self.server_name)
  1925. or (not self.map.host_matching and domain_part == self.subdomain)
  1926. ):
  1927. return f"{self.script_name.rstrip('/')}/{path.lstrip('/')}"
  1928. scheme = f"{url_scheme}:" if url_scheme else ""
  1929. return f"{scheme}//{host}{self.script_name[:-1]}/{path.lstrip('/')}"