"""Pylons' WSGI middlewares""" import os.path import urllib from paste.errordocument import StatusBasedForward from paste.recursive import RecursiveMiddleware from paste.urlparser import StaticURLParser from paste.deploy.converters import asbool from webhelpers.rails.asset_tag import javascript_path media_path = os.path.join(os.path.dirname(__file__), 'media') class StaticJavascripts(object): """Middleware for intercepting requests for WebHelpers' included javascript files. Triggered when PATH_INFO begins with '/javascripts/'. """ def __init__(self): self.javascripts_app = \ StaticURLParser(os.path.dirname(javascript_path)) def __call__(self, environ, start_response): if environ.get('PATH_INFO', '').startswith('/javascripts/'): return self.javascripts_app(environ, start_response) else: return self.javascripts_app.not_found(environ, start_response) def ErrorHandler(app, global_conf, **errorware): """ErrorHandler Toggle If debug is enabled, this function will return the app wrapped in our customized Paste EvalException middleware we have called the ``PylonsEvalException``. Otherwise, the app will be wrapped in the Paste ErrorMiddleware, and the ``errorware`` dict will be passed into it. """ if asbool(global_conf.get('debug')): from pylons.error import PylonsEvalException app = PylonsEvalException(app, global_conf, **errorware) else: from paste.exceptions.errormiddleware import ErrorMiddleware if 'error_template' in errorware: del errorware['error_template'] app = ErrorMiddleware(app, global_conf, **errorware) return app def error_mapper(code, message, environ, global_conf=None, **kw): if environ.get('pylons.error_call'): return None else: environ['pylons.error_call'] = True if global_conf is None: global_conf = {} codes = [401, 403, 404] if not asbool(global_conf.get('debug')): codes.append(500) if code in codes: # StatusBasedForward expects a relative URL (no SCRIPT_NAME) url = '/error/document/?%s' % (urllib.urlencode({'message': message, 'code': code})) return url def ErrorDocuments(app, global_conf=None, mapper=None, **kw): """Wraps the app in error docs using Paste RecursiveMiddleware and ErrorDocumentsMiddleware All the args are passed directly into the ErrorDocumentsMiddleware. If no mapper is given, a default error_mapper is passed in. """ if global_conf is None: global_conf = {} if mapper is None: mapper = error_mapper return RecursiveMiddleware(StatusBasedForward(app, global_conf=global_conf, mapper=mapper, **kw)) error_document_template = """\
s/error/img/logo.gif)