Beispiel #1
0
def ErrorDocuments(app, global_conf, mapper, **kw):
    """Wraps the app in error docs using Paste RecursiveMiddleware and
    ErrorDocumentsMiddleware
    """
    if global_conf is None:
        global_conf = {}

    return RecursiveMiddleware(
        StatusBasedForward(app, global_conf=global_conf, mapper=mapper, **kw))
Beispiel #2
0
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))
Beispiel #3
0
def make_forward_handler(
    app,
    auth_conf,
    app_conf=None,
    global_conf=None,
    prefix='authkit.forward',
):
    if not auth_conf.has_key('internalpath'):
        raise AuthKitConfigError("No %sinternalpath key specified" % prefix)
    app = MultiHandler(app)
    app.add_method('forward', Redirect, auth_conf['internalpath'])
    app.add_checker('forward', status_checker)
    app = MyRecursive(RecursiveMiddleware(app))
    return app
Beispiel #4
0
def test_forward():
    app = forward(error_docs_app, codes={404: '/error'})
    app = TestApp(RecursiveMiddleware(app))
    res = app.get('')
    assert res.header('content-type') == 'text/plain'
    assert res.full_status == '200 OK'
    assert 'requested page returned' in res
    res = app.get('/error')
    assert res.header('content-type') == 'text/plain'
    assert res.full_status == '200 OK'
    assert 'Page not found' in res
    res = app.get('/not_found', status=404)
    assert res.header('content-type') == 'text/plain'
    assert res.full_status == '404 Not found'
    # Note changed response
    assert 'Page not found' in res
def forward(app, codes):
    """
    Intercepts a response with a particular status code and returns the
    content from a specified URL instead.

    The arguments are:

    ``app``
        The WSGI application or middleware chain.

    ``codes``
        A dictionary of integer status codes and the URL to be displayed
        if the response uses that code.

    For example, you might want to create a static file to display a
    "File Not Found" message at the URL ``/error404.html`` and then use
    ``forward`` middleware to catch all 404 status codes and display the page
    you created. In this example ``app`` is your exisiting WSGI
    applicaiton::

        from paste.errordocument import forward
        app = forward(app, codes={404:'/error404.html'})

    """
    for code in codes:
        if not isinstance(code, int):
            raise TypeError('All status codes should be type int. '
                '%s is not valid'%repr(code))

    def error_codes_mapper(code, message, environ, global_conf, codes):
        if codes.has_key(code):
            return codes[code]
        else:
            return None

    #return _StatusBasedRedirect(app, error_codes_mapper, codes=codes)
    return RecursiveMiddleware(
        StatusBasedForward(
            app,
            error_codes_mapper,
            codes=codes,
        )
    )
Beispiel #6
0
def forward(app):
    app = TestApp(RecursiveMiddleware(app))
    res = app.get('')
    assert res.header('content-type') == 'text/plain'
    assert res.full_status == '200 OK'
    assert 'requested page returned' in res
    res = app.get('/error')
    assert res.header('content-type') == 'text/plain'
    assert res.full_status == '200 OK'
    assert 'Page not found' in res
    res = app.get('/not_found')
    assert res.header('content-type') == 'text/plain'
    assert res.full_status == '200 OK'
    assert 'Page not found' in res
    try:
        res = app.get('/recurse')
    except AssertionError as e:
        if str(e).startswith('Forwarding loop detected'):
            pass
        else:
            raise AssertionError('Failed to detect forwarding loop')
Beispiel #7
0
def test_ForwardRequest_factory():

    from paste.errordocument import StatusKeeper

    class TestForwardRequestMiddleware(Middleware):
        def __call__(self, environ, start_response):
            if environ['PATH_INFO'] != '/not_found':
                return self.app(environ, start_response)
            environ['PATH_INFO'] = self.url

            def factory(app):
                return StatusKeeper(app,
                                    status='404 Not Found',
                                    url='/error',
                                    headers=[])

            raise ForwardRequestException(factory=factory)

    app = TestForwardRequestMiddleware(error_docs_app)
    app = TestApp(RecursiveMiddleware(app))
    res = app.get('')
    assert res.header('content-type') == 'text/plain'
    assert res.full_status == '200 OK'
    assert 'requested page returned' in res
    res = app.get('/error')
    assert res.header('content-type') == 'text/plain'
    assert res.full_status == '200 OK'
    assert 'Page not found' in res
    res = app.get('/not_found', status=404)
    assert res.header('content-type') == 'text/plain'
    assert res.full_status == '404 Not Found'  # Different status
    assert 'Page not found' in res
    try:
        res = app.get('/recurse')
    except AssertionError as e:
        if str(e).startswith('Forwarding loop detected'):
            pass
        else:
            raise AssertionError('Failed to detect forwarding loop')
Beispiel #8
0
def make_forward_handler(
    app,
    auth_conf,
    app_conf=None,
    global_conf=None,
    prefix='authkit.forward',
):
    signin_path = None
    if auth_conf.has_key('internalpath'):
        warnings.warn(
            'The %sinternalpath key is deprecated. Please use '
            '%ssigninpath.' % (prefix, prefix), DeprecationWarning, 2)
        signin_path = auth_conf['internalpath']
    elif auth_conf.has_key('signinpath'):
        signin_path = auth_conf['signinpath']
    else:
        raise AuthKitConfigError("No %ssigninpath key specified" % prefix)
    app = MultiHandler(app)
    app.add_method('forward', Redirect, signin_path)
    app.add_checker('forward', status_checker)
    app = MyRecursive(RecursiveMiddleware(app))
    return app
Beispiel #9
0
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
    """Create a Pylons WSGI application and return it

    ``global_conf``
        The inherited configuration for this application. Normally from
        the [DEFAULT] section of the Paste ini file.

    ``full_stack``
        Whether this application provides a full WSGI stack (by default,
        meaning it handles its own exceptions and errors). Disable
        full_stack when this application is "managed" by another WSGI
        middleware.

    ``static_files``
        Whether this application serves its own static files; disable
        when another web server is responsible for serving them.

    ``app_conf``
        The application's local configuration. Normally specified in
        the [app:<name>] section of the Paste ini file (where <name>
        defaults to main).

    """
    # Configure the Pylons environment
    load_environment(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp()

    # Routing/Session/Cache Middleware
    app = RoutesMiddleware(app, config['routes.map'])
    app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)

    # Needed by authkit
    app = RecursiveMiddleware(app, global_conf)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)

    # Ponies!
    app = PonyMiddleware(app)

    # CUSTOM MIDDLEWARE END

    if asbool(full_stack):
        # Handle Python exceptions
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

        app = authkit.authenticate.middleware(app, app_conf)

        # Display error documents for 401, 403, 404 status codes (and
        # 500 when debug is disabled)
        if asbool(config['debug']):
            app = StatusCodeRedirect(app)
        else:
            app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])

    # Establish the Registry for this application
    app = RegistryManager(app)

    if asbool(static_files):
        # Serve static files
        static_app = StaticURLParser(config['pylons.paths']['static_files'])
        app = Cascade([static_app, app])

    return app