routing.py 72 KB

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