PageRenderTime 31ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Paste-1.7.5.1-py2.6.egg/paste/errordocument.py

https://github.com/renfers/ageliaco.tracker
Python | 383 lines | 357 code | 2 blank | 24 comment | 0 complexity | a16abcea04a96dabe2bd28e6c4f9cb50 MD5 | raw file
  1. # (c) 2005-2006 James Gardner <james@pythonweb.org>
  2. # This module is part of the Python Paste Project and is released under
  3. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  4. """
  5. Middleware to display error documents for certain status codes
  6. The middleware in this module can be used to intercept responses with
  7. specified status codes and internally forward the request to an appropriate
  8. URL where the content can be displayed to the user as an error document.
  9. """
  10. import warnings
  11. import sys
  12. from urlparse import urlparse
  13. from paste.recursive import ForwardRequestException, RecursiveMiddleware, RecursionLoop
  14. from paste.util import converters
  15. from paste.response import replace_header
  16. def forward(app, codes):
  17. """
  18. Intercepts a response with a particular status code and returns the
  19. content from a specified URL instead.
  20. The arguments are:
  21. ``app``
  22. The WSGI application or middleware chain.
  23. ``codes``
  24. A dictionary of integer status codes and the URL to be displayed
  25. if the response uses that code.
  26. For example, you might want to create a static file to display a
  27. "File Not Found" message at the URL ``/error404.html`` and then use
  28. ``forward`` middleware to catch all 404 status codes and display the page
  29. you created. In this example ``app`` is your exisiting WSGI
  30. applicaiton::
  31. from paste.errordocument import forward
  32. app = forward(app, codes={404:'/error404.html'})
  33. """
  34. for code in codes:
  35. if not isinstance(code, int):
  36. raise TypeError('All status codes should be type int. '
  37. '%s is not valid'%repr(code))
  38. def error_codes_mapper(code, message, environ, global_conf, codes):
  39. if codes.has_key(code):
  40. return codes[code]
  41. else:
  42. return None
  43. #return _StatusBasedRedirect(app, error_codes_mapper, codes=codes)
  44. return RecursiveMiddleware(
  45. StatusBasedForward(
  46. app,
  47. error_codes_mapper,
  48. codes=codes,
  49. )
  50. )
  51. class StatusKeeper(object):
  52. def __init__(self, app, status, url, headers):
  53. self.app = app
  54. self.status = status
  55. self.url = url
  56. self.headers = headers
  57. def __call__(self, environ, start_response):
  58. def keep_status_start_response(status, headers, exc_info=None):
  59. for header, value in headers:
  60. if header.lower() == 'set-cookie':
  61. self.headers.append((header, value))
  62. else:
  63. replace_header(self.headers, header, value)
  64. return start_response(self.status, self.headers, exc_info)
  65. parts = self.url.split('?')
  66. environ['PATH_INFO'] = parts[0]
  67. if len(parts) > 1:
  68. environ['QUERY_STRING'] = parts[1]
  69. else:
  70. environ['QUERY_STRING'] = ''
  71. #raise Exception(self.url, self.status)
  72. try:
  73. return self.app(environ, keep_status_start_response)
  74. except RecursionLoop, e:
  75. environ['wsgi.errors'].write('Recursion error getting error page: %s\n' % e)
  76. keep_status_start_response('500 Server Error', [('Content-type', 'text/plain')], sys.exc_info())
  77. return ['Error: %s. (Error page could not be fetched)'
  78. % self.status]
  79. class StatusBasedForward(object):
  80. """
  81. Middleware that lets you test a response against a custom mapper object to
  82. programatically determine whether to internally forward to another URL and
  83. if so, which URL to forward to.
  84. If you don't need the full power of this middleware you might choose to use
  85. the simpler ``forward`` middleware instead.
  86. The arguments are:
  87. ``app``
  88. The WSGI application or middleware chain.
  89. ``mapper``
  90. A callable that takes a status code as the
  91. first parameter, a message as the second, and accepts optional environ,
  92. global_conf and named argments afterwards. It should return a
  93. URL to forward to or ``None`` if the code is not to be intercepted.
  94. ``global_conf``
  95. Optional default configuration from your config file. If ``debug`` is
  96. set to ``true`` a message will be written to ``wsgi.errors`` on each
  97. internal forward stating the URL forwarded to.
  98. ``**params``
  99. Optional, any other configuration and extra arguments you wish to
  100. pass which will in turn be passed back to the custom mapper object.
  101. Here is an example where a ``404 File Not Found`` status response would be
  102. redirected to the URL ``/error?code=404&message=File%20Not%20Found``. This
  103. could be useful for passing the status code and message into another
  104. application to display an error document:
  105. .. code-block:: python
  106. from paste.errordocument import StatusBasedForward
  107. from paste.recursive import RecursiveMiddleware
  108. from urllib import urlencode
  109. def error_mapper(code, message, environ, global_conf, kw)
  110. if code in [404, 500]:
  111. params = urlencode({'message':message, 'code':code})
  112. url = '/error?'%(params)
  113. return url
  114. else:
  115. return None
  116. app = RecursiveMiddleware(
  117. StatusBasedForward(app, mapper=error_mapper),
  118. )
  119. """
  120. def __init__(self, app, mapper, global_conf=None, **params):
  121. if global_conf is None:
  122. global_conf = {}
  123. # @@: global_conf shouldn't really come in here, only in a
  124. # separate make_status_based_forward function
  125. if global_conf:
  126. self.debug = converters.asbool(global_conf.get('debug', False))
  127. else:
  128. self.debug = False
  129. self.application = app
  130. self.mapper = mapper
  131. self.global_conf = global_conf
  132. self.params = params
  133. def __call__(self, environ, start_response):
  134. url = []
  135. writer = []
  136. def change_response(status, headers, exc_info=None):
  137. status_code = status.split(' ')
  138. try:
  139. code = int(status_code[0])
  140. except (ValueError, TypeError):
  141. raise Exception(
  142. 'StatusBasedForward middleware '
  143. 'received an invalid status code %s'%repr(status_code[0])
  144. )
  145. message = ' '.join(status_code[1:])
  146. new_url = self.mapper(
  147. code,
  148. message,
  149. environ,
  150. self.global_conf,
  151. **self.params
  152. )
  153. if not (new_url == None or isinstance(new_url, str)):
  154. raise TypeError(
  155. 'Expected the url to internally '
  156. 'redirect to in the StatusBasedForward mapper'
  157. 'to be a string or None, not %r' % new_url)
  158. if new_url:
  159. url.append([new_url, status, headers])
  160. # We have to allow the app to write stuff, even though
  161. # we'll ignore it:
  162. return [].append
  163. else:
  164. return start_response(status, headers, exc_info)
  165. app_iter = self.application(environ, change_response)
  166. if url:
  167. if hasattr(app_iter, 'close'):
  168. app_iter.close()
  169. def factory(app):
  170. return StatusKeeper(app, status=url[0][1], url=url[0][0],
  171. headers=url[0][2])
  172. raise ForwardRequestException(factory=factory)
  173. else:
  174. return app_iter
  175. def make_errordocument(app, global_conf, **kw):
  176. """
  177. Paste Deploy entry point to create a error document wrapper.
  178. Use like::
  179. [filter-app:main]
  180. use = egg:Paste#errordocument
  181. next = real-app
  182. 500 = /lib/msg/500.html
  183. 404 = /lib/msg/404.html
  184. """
  185. map = {}
  186. for status, redir_loc in kw.items():
  187. try:
  188. status = int(status)
  189. except ValueError:
  190. raise ValueError('Bad status code: %r' % status)
  191. map[status] = redir_loc
  192. forwarder = forward(app, map)
  193. return forwarder
  194. __pudge_all__ = [
  195. 'forward',
  196. 'make_errordocument',
  197. 'empty_error',
  198. 'make_empty_error',
  199. 'StatusBasedForward',
  200. ]
  201. ###############################################################################
  202. ## Deprecated
  203. ###############################################################################
  204. def custom_forward(app, mapper, global_conf=None, **kw):
  205. """
  206. Deprectated; use StatusBasedForward instead.
  207. """
  208. warnings.warn(
  209. "errordocuments.custom_forward has been deprecated; please "
  210. "use errordocuments.StatusBasedForward",
  211. DeprecationWarning, 2)
  212. if global_conf is None:
  213. global_conf = {}
  214. return _StatusBasedRedirect(app, mapper, global_conf, **kw)
  215. class _StatusBasedRedirect(object):
  216. """
  217. Deprectated; use StatusBasedForward instead.
  218. """
  219. def __init__(self, app, mapper, global_conf=None, **kw):
  220. warnings.warn(
  221. "errordocuments._StatusBasedRedirect has been deprecated; please "
  222. "use errordocuments.StatusBasedForward",
  223. DeprecationWarning, 2)
  224. if global_conf is None:
  225. global_conf = {}
  226. self.application = app
  227. self.mapper = mapper
  228. self.global_conf = global_conf
  229. self.kw = kw
  230. self.fallback_template = """
  231. <html>
  232. <head>
  233. <title>Error %(code)s</title>
  234. </html>
  235. <body>
  236. <h1>Error %(code)s</h1>
  237. <p>%(message)s</p>
  238. <hr>
  239. <p>
  240. Additionally an error occurred trying to produce an
  241. error document. A description of the error was logged
  242. to <tt>wsgi.errors</tt>.
  243. </p>
  244. </body>
  245. </html>
  246. """
  247. def __call__(self, environ, start_response):
  248. url = []
  249. code_message = []
  250. try:
  251. def change_response(status, headers, exc_info=None):
  252. new_url = None
  253. parts = status.split(' ')
  254. try:
  255. code = int(parts[0])
  256. except (ValueError, TypeError):
  257. raise Exception(
  258. '_StatusBasedRedirect middleware '
  259. 'received an invalid status code %s'%repr(parts[0])
  260. )
  261. message = ' '.join(parts[1:])
  262. new_url = self.mapper(
  263. code,
  264. message,
  265. environ,
  266. self.global_conf,
  267. self.kw
  268. )
  269. if not (new_url == None or isinstance(new_url, str)):
  270. raise TypeError(
  271. 'Expected the url to internally '
  272. 'redirect to in the _StatusBasedRedirect error_mapper'
  273. 'to be a string or None, not %s'%repr(new_url)
  274. )
  275. if new_url:
  276. url.append(new_url)
  277. code_message.append([code, message])
  278. return start_response(status, headers, exc_info)
  279. app_iter = self.application(environ, change_response)
  280. except:
  281. try:
  282. import sys
  283. error = str(sys.exc_info()[1])
  284. except:
  285. error = ''
  286. try:
  287. code, message = code_message[0]
  288. except:
  289. code, message = ['', '']
  290. environ['wsgi.errors'].write(
  291. 'Error occurred in _StatusBasedRedirect '
  292. 'intercepting the response: '+str(error)
  293. )
  294. return [self.fallback_template
  295. % {'message': message, 'code': code}]
  296. else:
  297. if url:
  298. url_ = url[0]
  299. new_environ = {}
  300. for k, v in environ.items():
  301. if k != 'QUERY_STRING':
  302. new_environ['QUERY_STRING'] = urlparse(url_)[4]
  303. else:
  304. new_environ[k] = v
  305. class InvalidForward(Exception):
  306. pass
  307. def eat_start_response(status, headers, exc_info=None):
  308. """
  309. We don't want start_response to do anything since it
  310. has already been called
  311. """
  312. if status[:3] != '200':
  313. raise InvalidForward(
  314. "The URL %s to internally forward "
  315. "to in order to create an error document did not "
  316. "return a '200' status code." % url_
  317. )
  318. forward = environ['paste.recursive.forward']
  319. old_start_response = forward.start_response
  320. forward.start_response = eat_start_response
  321. try:
  322. app_iter = forward(url_, new_environ)
  323. except InvalidForward, e:
  324. code, message = code_message[0]
  325. environ['wsgi.errors'].write(
  326. 'Error occurred in '
  327. '_StatusBasedRedirect redirecting '
  328. 'to new URL: '+str(url[0])
  329. )
  330. return [
  331. self.fallback_template%{
  332. 'message':message,
  333. 'code':code,
  334. }
  335. ]
  336. else:
  337. forward.start_response = old_start_response
  338. return app_iter
  339. else:
  340. return app_iter