0001from paste.wsgilib import intercept_output
0002from paste.response import header_value
0003from context import Context
0004import simplelog
0005
0006class OverlayMiddleware(object):
0007
0008    def __init__(self, app, log=None):
0009        self.app = app
0010        self.log = log
0011
0012    def __call__(self, environ, start_response):
0013        pristine_environ = environ.copy()
0014        status, headers, body = intercept_output(
0015                    environ, self.app,
0016                    self.test_content_type,
0017                    start_response)
0018        if status is None:
0019            # condition wasn't met
0020            return body
0021        def fetch(uri):
0022            return self.fetch_uri(uri, pristine_environ)
0023        if self.log == 'wsgi.errors':
0024            log = simplelog.FileLog(environ['wsgi.errors'])
0025        else:
0026            log = self.log
0027        context = Context(fetch, log=log)
0028        uri = (pristine_environ.get('SCRIPT_NAME', '')
0029               + pristine_environ.get('PATH_INFO', ''))
0030        context.add_page(uri, headers, body, True)
0031        new_body = context.render()
0032        start_response(status, headers)
0033        return [new_body]
0034
0035    def test_content_type(self, status, headers):
0036        content_type = header_value(headers, 'content-type')
0037        return content_type.startswith('text/html')
0038
0039    def fetch_uri(self, uri, pristine_environ):
0040        environ = pristine_environ.copy()
0041        script_name = environ.get('SCRIPT_NAME', '')
0042        assert uri.startswith(script_name)
0043        path_info = uri[len(script_name):]
0044        environ['PATH_INFO'] = path_info
0045        status, headers, body = intercept_output(
0046            environ, self.app)
0047        return headers, body
0048
0049def make_middleware(global_conf, app, log=None):
0050    if log not in (None, 'stderr', 'stdout', 'wsgi.errors', 'inline'):
0051        raise ValueError(
0052            "Unexpected value for log: %r" % log)
0053    return OverlayMiddleware(app, log=log)