routing.py 77 KB

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