routing.py 63 KB

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