urlmap.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
  2. # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
  3. """
  4. Map URL prefixes to WSGI applications. See ``URLMap``
  5. """
  6. from UserDict import DictMixin
  7. import re
  8. import os
  9. from paste import httpexceptions
  10. __all__ = ['URLMap', 'PathProxyURLMap']
  11. def urlmap_factory(loader, global_conf, **local_conf):
  12. if 'not_found_app' in local_conf:
  13. not_found_app = local_conf.pop('not_found_app')
  14. else:
  15. not_found_app = global_conf.get('not_found_app')
  16. if not_found_app:
  17. not_found_app = loader.get_app(not_found_app, global_conf=global_conf)
  18. urlmap = URLMap(not_found_app=not_found_app)
  19. for path, app_name in local_conf.items():
  20. path = parse_path_expression(path)
  21. app = loader.get_app(app_name, global_conf=global_conf)
  22. urlmap[path] = app
  23. return urlmap
  24. def parse_path_expression(path):
  25. """
  26. Parses a path expression like 'domain foobar.com port 20 /' or
  27. just '/foobar' for a path alone. Returns as an address that
  28. URLMap likes.
  29. """
  30. parts = path.split()
  31. domain = port = path = None
  32. while parts:
  33. if parts[0] == 'domain':
  34. parts.pop(0)
  35. if not parts:
  36. raise ValueError("'domain' must be followed with a domain name")
  37. if domain:
  38. raise ValueError("'domain' given twice")
  39. domain = parts.pop(0)
  40. elif parts[0] == 'port':
  41. parts.pop(0)
  42. if not parts:
  43. raise ValueError("'port' must be followed with a port number")
  44. if port:
  45. raise ValueError("'port' given twice")
  46. port = parts.pop(0)
  47. else:
  48. if path:
  49. raise ValueError("more than one path given (have %r, got %r)"
  50. % (path, parts[0]))
  51. path = parts.pop(0)
  52. s = ''
  53. if domain:
  54. s = 'http://%s' % domain
  55. if port:
  56. if not domain:
  57. raise ValueError("If you give a port, you must also give a domain")
  58. s += ':' + port
  59. if path:
  60. if s:
  61. s += '/'
  62. s += path
  63. return s
  64. class URLMap(DictMixin):
  65. """
  66. URLMap instances are dictionary-like object that dispatch to one
  67. of several applications based on the URL.
  68. The dictionary keys are URLs to match (like
  69. ``PATH_INFO.startswith(url)``), and the values are applications to
  70. dispatch to. URLs are matched most-specific-first, i.e., longest
  71. URL first. The ``SCRIPT_NAME`` and ``PATH_INFO`` environmental
  72. variables are adjusted to indicate the new context.
  73. URLs can also include domains, like ``http://blah.com/foo``, or as
  74. tuples ``('blah.com', '/foo')``. This will match domain names; without
  75. the ``http://domain`` or with a domain of ``None`` any domain will be
  76. matched (so long as no other explicit domain matches). """
  77. def __init__(self, not_found_app=None):
  78. self.applications = []
  79. if not not_found_app:
  80. not_found_app = self.not_found_app
  81. self.not_found_application = not_found_app
  82. norm_url_re = re.compile('//+')
  83. domain_url_re = re.compile('^(http|https)://')
  84. def not_found_app(self, environ, start_response):
  85. mapper = environ.get('paste.urlmap_object')
  86. if mapper:
  87. matches = [p for p, a in mapper.applications]
  88. extra = 'defined apps: %s' % (
  89. ',\n '.join(map(repr, matches)))
  90. else:
  91. extra = ''
  92. extra += '\nSCRIPT_NAME: %r' % environ.get('SCRIPT_NAME')
  93. extra += '\nPATH_INFO: %r' % environ.get('PATH_INFO')
  94. extra += '\nHTTP_HOST: %r' % environ.get('HTTP_HOST')
  95. app = httpexceptions.HTTPNotFound(
  96. environ['PATH_INFO'],
  97. comment=extra).wsgi_application
  98. return app(environ, start_response)
  99. def normalize_url(self, url, trim=True):
  100. if isinstance(url, (list, tuple)):
  101. domain = url[0]
  102. url = self.normalize_url(url[1])[1]
  103. return domain, url
  104. assert (not url or url.startswith('/')
  105. or self.domain_url_re.search(url)), (
  106. "URL fragments must start with / or http:// (you gave %r)" % url)
  107. match = self.domain_url_re.search(url)
  108. if match:
  109. url = url[match.end():]
  110. if '/' in url:
  111. domain, url = url.split('/', 1)
  112. url = '/' + url
  113. else:
  114. domain, url = url, ''
  115. else:
  116. domain = None
  117. url = self.norm_url_re.sub('/', url)
  118. if trim:
  119. url = url.rstrip('/')
  120. return domain, url
  121. def sort_apps(self):
  122. """
  123. Make sure applications are sorted with longest URLs first
  124. """
  125. def key(app_desc):
  126. (domain, url), app = app_desc
  127. if not domain:
  128. # Make sure empty domains sort last:
  129. return '\xff', -len(url)
  130. else:
  131. return domain, -len(url)
  132. apps = [(key(desc), desc) for desc in self.applications]
  133. apps.sort()
  134. self.applications = [desc for (sortable, desc) in apps]
  135. def __setitem__(self, url, app):
  136. if app is None:
  137. try:
  138. del self[url]
  139. except KeyError:
  140. pass
  141. return
  142. dom_url = self.normalize_url(url)
  143. if dom_url in self:
  144. del self[dom_url]
  145. self.applications.append((dom_url, app))
  146. self.sort_apps()
  147. def __getitem__(self, url):
  148. dom_url = self.normalize_url(url)
  149. for app_url, app in self.applications:
  150. if app_url == dom_url:
  151. return app
  152. raise KeyError(
  153. "No application with the url %r (domain: %r; existing: %s)"
  154. % (url[1], url[0] or '*', self.applications))
  155. def __delitem__(self, url):
  156. url = self.normalize_url(url)
  157. for app_url, app in self.applications:
  158. if app_url == url:
  159. self.applications.remove((app_url, app))
  160. break
  161. else:
  162. raise KeyError(
  163. "No application with the url %r" % (url,))
  164. def keys(self):
  165. return [app_url for app_url, app in self.applications]
  166. def __call__(self, environ, start_response):
  167. host = environ.get('HTTP_HOST', environ.get('SERVER_NAME')).lower()
  168. if ':' in host:
  169. host, port = host.split(':', 1)
  170. else:
  171. if environ['wsgi.url_scheme'] == 'http':
  172. port = '80'
  173. else:
  174. port = '443'
  175. path_info = environ.get('PATH_INFO')
  176. path_info = self.normalize_url(path_info, False)[1]
  177. for (domain, app_url), app in self.applications:
  178. if domain and domain != host and domain != host+':'+port:
  179. continue
  180. if (path_info == app_url
  181. or path_info.startswith(app_url + '/')):
  182. environ['SCRIPT_NAME'] += app_url
  183. environ['PATH_INFO'] = path_info[len(app_url):]
  184. return app(environ, start_response)
  185. environ['paste.urlmap_object'] = self
  186. return self.not_found_application(environ, start_response)
  187. class PathProxyURLMap(object):
  188. """
  189. This is a wrapper for URLMap that catches any strings that
  190. are passed in as applications; these strings are treated as
  191. filenames (relative to `base_path`) and are passed to the
  192. callable `builder`, which will return an application.
  193. This is intended for cases when configuration files can be
  194. treated as applications.
  195. `base_paste_url` is the URL under which all applications added through
  196. this wrapper must go. Use ``""`` if you want this to not
  197. change incoming URLs.
  198. """
  199. def __init__(self, map, base_paste_url, base_path, builder):
  200. self.map = map
  201. self.base_paste_url = self.map.normalize_url(base_paste_url)
  202. self.base_path = base_path
  203. self.builder = builder
  204. def __setitem__(self, url, app):
  205. if isinstance(app, (str, unicode)):
  206. app_fn = os.path.join(self.base_path, app)
  207. app = self.builder(app_fn)
  208. url = self.map.normalize_url(url)
  209. # @@: This means http://foo.com/bar will potentially
  210. # match foo.com, but /base_paste_url/bar, which is unintuitive
  211. url = (url[0] or self.base_paste_url[0],
  212. self.base_paste_url[1] + url[1])
  213. self.map[url] = app
  214. def __getattr__(self, attr):
  215. return getattr(self.map, attr)
  216. # This is really the only settable attribute
  217. def not_found_application__get(self):
  218. return self.map.not_found_application
  219. def not_found_application__set(self, value):
  220. self.map.not_found_application = value
  221. not_found_application = property(not_found_application__get,
  222. not_found_application__set)