Ejemplo n.º 1
0
    def command(self):
        try:
            if self.options.proctitle:
                import setproctitle
                setproctitle.setproctitle("paster " + self.options.proctitle)
        except ImportError:
            pass

        here_dir = os.getcwd()

        is_standalone = self.args[0].lower() == 'standalone'
        if is_standalone:
            load_environment(setup_globals=False)
        else:
            config_name = 'config:%s' % self.args[0]

            conf = appconfig(config_name, relative_to=here_dir)
            conf.global_conf['running_as_script'] = True
            conf.update(
                dict(app_conf=conf.local_conf, global_conf=conf.global_conf))
            paste.deploy.config.CONFIG.push_thread_config(conf)

            load_environment(conf.global_conf, conf.local_conf)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        if not is_standalone:
            wsgiapp = RegistryManager(RedditApp())
        else:
            # in standalone mode we don't have an ini so we can't use
            # RedditApp since it imports all the fancy controllers.
            wsgiapp = RegistryManager(PylonsApp())
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)

        loaded_namespace = {}

        if self.args[1:]:
            execfile(self.args[1], loaded_namespace)

        if self.options.command:
            exec self.options.command in loaded_namespace
Ejemplo n.º 2
0
 def setUp(self):
     TestWSGIController.setUp(self)
     app = ControllerWrap(ProtectedController)
     app = SetupCacheGlobal(app, self.environ, setup_session=True)
     app = SessionMiddleware(app, {}, data_dir=session_dir)
     app = RegistryManager(app)
     self.app = TestApp(app)
Ejemplo n.º 3
0
 def __init__(self, *args, **kargs):
     TestWSGIController.__init__(self, *args, **kargs)
     self.baseenviron = {}
     app = ControllerWrap(FilteredWSGIController)
     app = self.sap = SetupCacheGlobal(app, self.baseenviron)
     app = RegistryManager(app)
     self.app = TestApp(app)
Ejemplo n.º 4
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
    config = load_environment(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp(config=config)

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

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)

    if asbool(full_stack):
        
        # permission = ValidAuthKitUser()
        # app = authkit.authorize.middleware(app, permission)
        app = authkit.authenticate.middleware(app, app_conf)
        
        # Handle Python exceptions
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

        # 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])
    app.config = config
    return app
Ejemplo n.º 5
0
def make_wsgi(profile='Default'):

    config.appinit(settingsmod, profile)

    app = WSGIApp()

    app = ElixirApp(app)

    app = SessionMiddleware(app, **dict(settings.beaker))

    app = RegistryManager(app)

    # serve static files from main app and supporting apps (need to reverse order b/c
    # middleware stack is run in bottom up order).  This works b/c if a
    # static file isn't found, the ShardDataMiddleware just forwards the request
    # to the next app.
    for appname in config.appslist(reverse=True):
        app_py_mod = __import__(appname)
        fs_static_path = path.join(path.dirname(app_py_mod.__file__), 'static')
        static_map = {routing.add_prefix('/'): fs_static_path}
        app = SharedDataMiddleware(app, static_map)

    # show nice stack traces and debug output if enabled
    if settings.debugger.enabled:
        app = DebuggedApplication(app, evalex=settings.debugger.interactive)

    return app
Ejemplo n.º 6
0
 def test_external_registry(self):
     config = {'moksha.registry': False}
     app = moksha.wsgi.middleware.make_moksha_middleware(self.app, config)
     from paste.registry import RegistryManager
     app = RegistryManager(app)
     response = webtest.TestApp(app).get('/')
     eq_(response.status, '200 OK')
Ejemplo n.º 7
0
def make_app(global_conf, full_stack=True, **app_conf):
    # load Pylons environment
    root = os.path.dirname(os.path.abspath(__file__))
    paths = dict(
        templates=[os.path.join(root, 'templates')],
    )
    config.init_app(global_conf, app_conf, paths=paths)
    config['pylons.package'] = 'tests.contrib.pylons.app'
    config['pylons.app_globals'] = AppGlobals()

    # set Pylons routes
    config['routes.map'] = create_routes()

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
    )

    # define a default middleware stack
    app = PylonsApp()
    app = RoutesMiddleware(app, config['routes.map'])
    app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)
    app = RegistryManager(app)
    return app
Ejemplo n.º 8
0
def make_app(global_conf, full_stack=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 or not 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.

    `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(base_wsgi_app=RedditApp)

    # CUSTOM MIDDLEWARE HERE (filtered by the error handling middlewares)

    # last thing first from here down
    app = CleanupMiddleware(app)

    app = LimitUploadSize(app)
    app = ProfileGraphMiddleware(app)
    app = ProfilingMiddleware(app)
    app = SourceViewMiddleware(app)

    app = DomainListingMiddleware(app)
    app = SubredditMiddleware(app)
    app = ExtensionMiddleware(app)
    app = DomainMiddleware(app)

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

        # Display error documents for 401, 403, 404 status codes (and 500 when
        # debug is disabled)
        app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf)

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

    # Static files
    javascripts_app = StaticJavascripts()
    static_app = StaticURLParser(config['pylons.paths']['static_files'])
    app = Cascade([static_app, javascripts_app, app])

    #add the rewrite rules
    app = RewriteMiddleware(app)

    return app
Ejemplo n.º 9
0
 def run(self, host=None, port=8080, debug=False):
     self.config.end()
     app = self.config.make_wsgi_app()
     if debug:
         app = EvalException(app)
     app = RegistryManager(app)
     serve(app, host, port)
Ejemplo n.º 10
0
def make_app(controller_klass, environ={}):
    """Creates a ``TestApp`` instance."""
    # The basic middleware:
    app = ControllerWrap(controller_klass)
    app = SetupCacheGlobal(app, environ, setup_cache=True, setup_session=True)
    app = RegistryManager(app)
    app = SessionMiddleware(app, {}, data_dir=session_dir)
    app = CacheMiddleware(app, {}, data_dir=os.path.join(data_dir, 'cache'))

    # We're not going to use groups or permissions-related predicates here:
    groups_adapters = None
    permissions_adapters = None

    # Setting repoze.who up:
    cookie = AuthTktCookiePlugin('secret', 'authtkt')
    identifiers = [('cookie', cookie)]

    app = setup_auth(app,
                     groups_adapters,
                     permissions_adapters,
                     identifiers=identifiers,
                     authenticators=[],
                     challengers=[],
                     skip_authentication=True)

    app = httpexceptions.make_middleware(app)
    return TestApp(app)
Ejemplo n.º 11
0
def make_app(global_conf,
             full_stack=True,
             static_files=True,
             include_cache_middleware=False,
             attribsafe=False,
             **app_conf):
    import pylons
    import pylons.configuration as configuration
    from pylons import url
    from pylons.decorators import jsonify
    from pylons.middleware import ErrorHandler, StatusCodeRedirect
    from pylons.error import handle_mako_error
    from pylons.wsgiapp import PylonsApp

    root = os.path.dirname(os.path.abspath(__file__))
    paths = dict(root=os.path.join(test_root, 'sample_controllers'),
                 controllers=os.path.join(test_root, 'sample_controllers',
                                          'controllers'),
                 templates=os.path.join(test_root, 'sample_controllers',
                                        'templates'))
    sys.path.append(test_root)

    config = configuration.PylonsConfig()
    config.init_app(global_conf,
                    app_conf,
                    package='sample_controllers',
                    paths=paths)
    map = Mapper(directory=config['pylons.paths']['controllers'])
    map.connect('/{controller}/{action}')
    config['routes.map'] = map

    class AppGlobals(object):
        pass

    config['pylons.app_globals'] = AppGlobals()

    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        imports=['from markupsafe import escape'])

    if attribsafe:
        config['pylons.strict_tmpl_context'] = False

    app = PylonsApp(config=config)
    app = RoutesMiddleware(app, config['routes.map'], singleton=False)
    if include_cache_middleware:
        app = CacheMiddleware(app, config)
    app = SessionMiddleware(app, config)

    if asbool(full_stack):
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
        if asbool(config['debug']):
            app = StatusCodeRedirect(app)
        else:
            app = StatusCodeRedirect(app, [401, 403, 404, 500])
    app = RegistryManager(app)

    app.config = config
    return app
Ejemplo n.º 12
0
def make_app(global_conf, full_stack=False, 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
    config = load_environment(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp(config=config)

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

    # At some point it seems that Pylons converts the Content-Type of any
    # response without a 200 OK status to 'text/html; charset=utf-8'.  Well
    # no more Pylons!  The HTML2JSONContentType middleware zaps those
    # nasty text/html content types and converts them to application/json!
    app = HTML2JSONContentType(app)

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

        # 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])
    app.config = config
    return app
Ejemplo n.º 13
0
 def __init__(self, *args, **kargs):
     TestWSGIController.__init__(self, *args, **kargs)
     self.baseenviron = {}
     self.baseenviron['pylons.routes_dict'] = {}
     app = ControllerWrap(BaseXMLRPCController)
     app = self.sap = SetupCacheGlobal(app, self.baseenviron)
     app = RegistryManager(app)
     self.app = TestApp(app)
Ejemplo n.º 14
0
def minimal_wsgi_stack(app):
    """
        returns a WSGI application wrapped in minimal middleware, mostly useful
        for internal testing
    """
    app = RegistrySetup(app, ag.app)
    app = RegistryManager(app)
    return app
Ejemplo n.º 15
0
def make_app(global_conf, full_stack=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 or not 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.

    ``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
    config = load_environment(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp(config=config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)

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

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

        # 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)

    # Static files (If running in production, and Apache or another web
    # server is handling this static content, remove the following 3 lines)
    static_app = StaticURLParser(
        config['pylons.paths']['static_files'],
        cache_max_age=31536000  # Cache it for one-year
    )
    app = Cascade([static_app, app])

    # Authentication Middleware
    app = multigate.authenticate.middleware(app, app_conf)

    app.config = config
    return app
Ejemplo n.º 16
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)

    # Teambox debugging.
    if config['debug']:
        app = TeamboxDebugMiddleware(app)

        # Production setup.
    else:
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

    # Handle special status codes.
    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])

    # Change the url scheme when needed.
    if config.has_key('url_scheme'):
        app = UrlSchemeMiddleware(app, config['url_scheme'])

    return app
Ejemplo n.º 17
0
 def __init__(self, *args, **kargs):
     from pylons.testutil import ControllerWrap, SetupCacheGlobal
     BasicWSGIController, FilteredWSGIController = make_controllers()
     TestWSGIController.__init__(self, *args, **kargs)
     self.baseenviron = {}
     app = ControllerWrap(FilteredWSGIController)
     app = self.sap = SetupCacheGlobal(app, self.baseenviron)
     app = RegistryManager(app)
     self.app = TestApp(app)
 def setUp(self):
     from pylons.testutil import ControllerWrap, SetupCacheGlobal
     ProtectedController = make_protected()
     TestWSGIController.setUp(self)
     app = ControllerWrap(ProtectedController)
     app = SetupCacheGlobal(app, self.environ, setup_session=True)
     app = SessionMiddleware(app, {}, data_dir=session_dir)
     app = RegistryManager(app)
     self.app = TestApp(app)
Ejemplo n.º 19
0
    def setUp(self):
        from pylons.testutil import ControllerWrap, SetupCacheGlobal
        ValidatingController = make_validating_controller()

        TestWSGIController.setUp(self)
        app = SetupCacheGlobal(ControllerWrap(ValidatingController),
                               self.environ)
        app = RegistryManager(app)
        self.app = TestApp(app)
Ejemplo n.º 20
0
def make_app(global_conf, full_stack=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 or not 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.

    ``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()

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
    #app = TransLogger(app)
    app = AuthenticationMiddleware(app)

    import pylons
    if pylons.__version__ >= "0.9.7":
        # Routing/Session/Cache Middleware
        from beaker.middleware import CacheMiddleware, SessionMiddleware
        from routes.middleware import RoutesMiddleware
        app = RoutesMiddleware(app, config['routes.map'])
        app = SessionMiddleware(app, config)
        app = CacheMiddleware(app, config)

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

        # 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, [401, 403, 404, 500])

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

    # Static files
    static_app = StaticURLParser(config['pylons.paths']['static_files'])
    app = Cascade([static_app, app])
    return app
Ejemplo n.º 21
0
 def setUp(self):
     TestWSGIController.setUp(self)
     from routes import Mapper
     map = Mapper()
     map.connect('/:action/:id')
     map.connect('/:controller/:action/:id')
     app = ControllerWrap(HttpsController)
     app = SetupCacheGlobal(app, self.environ, setup_cache=False)
     app = RoutesMiddleware(app, map)
     app = RegistryManager(app)
     self.app = TestApp(app)
Ejemplo n.º 22
0
    def __init__(self, *args, **kwargs):
        from pylons.testutil import ControllerWrap, SetupCacheGlobal

        BaseJSONRPCController = make_basejsonrpc()
        TestWSGIController.__init__(self, *args, **kwargs)
        self.baseenviron = {}
        self.baseenviron['pylons.routes_dict'] = {}
        app = ControllerWrap(BaseJSONRPCController)
        app = self.sap = SetupCacheGlobal(app, self.baseenviron)
        app = RegistryManager(app)
        self.app = TestApp(app)
Ejemplo n.º 23
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 or not 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.

    ``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()

    app = RoutesMiddleware(app, config['routes.map'])
    app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)

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

        # 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, [401, 403, 404, 500])

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

    # Static files
    if asbool(static_files):
        static_app = StaticURLParser(config['pylons.paths']['static_files'])
        media_app = StaticURLParser(config['app_conf']['media_dir'])
        thumb_app = StaticURLParser(config['app_conf']['thumb_dir'])
        urlmap = URLMap()
        urlmap['/media'] = media_app
        urlmap['/thumb'] = thumb_app
        app = Cascade([urlmap, static_app, app])
    return app
Ejemplo n.º 24
0
def make_app( global_conf, full_stack = 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 or not 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.

    ``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
    # Overload with DIRAC app after the PYTHONPATH has been set
    from dirac.lib.DiracWebApp import DiracWebApp
    app = DiracWebApp()

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
    app = RoutesMiddleware( app, config['routes.map'] )
    app = SessionMiddleware( app, config )
    app = CacheMiddleware( app, config )

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

        # Display error documents for 401, 403, 404 status codes (and
        # 500 when debug is disabled)
        app = ErrorDocuments( app, global_conf, mapper = error_mapper, **app_conf )

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

    # Static files
    staticFiles = config['pylons.paths']['static_files']
    cascadeApps = []
    if type( staticFiles ) in ( types.ListType, types.TupleType ):
      for staticFile in staticFiles:
        cascadeApps.append( StaticURLParser( staticFile ) )
    else:
      cascadeApps.append( StaticURLParser( staticFiles ) )
    cascadeApps.extend( [ app ] )
    app = Cascade( cascadeApps )
    return app
Ejemplo n.º 25
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 or not 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.

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

    """
    # Apply compatibility patches
    patches.kombu_1_5_1_python_2_7_11()
    patches.inspect_getargspec()

    # Configure the Pylons environment
    config = load_environment(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp(config=config)
    if rhodecode.is_test:
        app = csrf.CSRFDetector(app)

    expected_origin = config.get('expected_origin')
    if expected_origin:
        # The API can be accessed from other Origins.
        app = csrf.OriginChecker(app,
                                 expected_origin,
                                 skip_urls=[routes.util.url_for('api')])

    if asbool(full_stack):

        # Appenlight monitoring and error handler
        app, appenlight_client = wrap_in_appenlight_if_enabled(app, config)

        # we want our low level middleware to get to the request ASAP. We don't
        # need any pylons stack middleware in them
        app = VCSMiddleware(app, config, appenlight_client)

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

    app.config = config

    return app
Ejemplo n.º 26
0
def make_app(global_conf, full_stack=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 or not 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.

	``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)
	
	if asbool(full_stack):
		# Display error documents for 401, 403, 404 status codes (and 500 when debug is disabled)
		if asbool(config['debug']):
			app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
		else:
			app = PrintErrors(app, global_conf, **config['pylons.errorware'])

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

	# Static files (If running in production, and Apache or another web 
	# server is handling this static content, remove the following 2 lines)
	static_app = StaticURLParser(config['pylons.paths']['static_files'])
	app = Cascade([static_app, app])
	app = GzipMiddleware(app, compresslevel=5)

	if asbool(config.get("nwrsc.onsite", False)):
		announcer = DatabaseAnnouncer(config.get('seriesdir', 'missing'))
		announcer.start()

	return app
Ejemplo n.º 27
0
def make_app(global_conf, full_stack=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 or not 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.

    ``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, False)

    # The Pylons WSGI app
    app = PylonsApp()
    app = RoutesMiddleware(app, config['routes.map'])
    app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
    if asbool(full_stack):
        # Handle Python exceptions
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

        # 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 config['pylons.app_globals'].OPT.compressionEnabled:
        app = gzipper(app, config['pylons.app_globals'].OPT.compressionLevel)
    # Static files
    static_app = StaticURLParser(config['pylons.paths']['static_files'])
    app = Cascade([static_app, app])
    prefix = config['pylons.app_globals'].OPT.urlPrefix
    if prefix and prefix.startswith('/') and len(prefix) > 1:
        app = PrefixMiddleware(app, global_conf, prefix=prefix)
    return app
Ejemplo n.º 28
0
def make_app(global_conf, full_stack=True, static_files=True, include_cache_middleware=False, attribsafe=False, **app_conf):
    import pylons
    import pylons.configuration as configuration
    from beaker.cache import CacheManager
    from beaker.middleware import SessionMiddleware, CacheMiddleware
    from nose.tools import raises
    from paste.registry import RegistryManager
    from paste.deploy.converters import asbool
    from pylons.decorators import jsonify
    from pylons.middleware import ErrorHandler, StatusCodeRedirect
    from pylons.wsgiapp import PylonsApp
    from routes import Mapper
    from routes.middleware import RoutesMiddleware
    
    paths = dict(root=os.path.join(test_root, 'sample_controllers'), controllers=os.path.join(test_root, 'sample_controllers', 'controllers'))

    config = configuration.pylons_config
    config.init_app(global_conf, app_conf, package='sample_controllers', paths=paths)
    map = Mapper(directory=config['pylons.paths']['controllers'])
    map.connect('/{controller}/{action}')
    map.connect('/test_func', controller='sample_controllers.controllers.hello:special_controller')
    map.connect('/test_empty', controller='sample_controllers.controllers.hello:empty_wsgi')
    config['routes.map'] = map
    
    class AppGlobals(object):
        def __init__(self):
            self.cache = 'Nothing here but a string'
    
    config['pylons.app_globals'] = AppGlobals()
    
    if attribsafe:
        config['pylons.strict_tmpl_context'] = False
    
    app = PylonsApp(config=config)
    app = RoutesMiddleware(app, config['routes.map'], singleton=False)
    if include_cache_middleware:
        app = CacheMiddleware(app, config)
    app = SessionMiddleware(app, config)

    if asbool(full_stack):
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
        if asbool(config['debug']):
            app = StatusCodeRedirect(app)
        else:
            app = StatusCodeRedirect(app, [401, 403, 404, 500])
    app = RegistryManager(app)

    app.config = config
    return app
Ejemplo n.º 29
0
def make_app(global_conf, full_stack=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 or not 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.

    ``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()

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)

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

    # AuthKit Support
    app = authkit.authenticate.middleware(app, app_conf)

    # Display error documents for 401, 403, 404 status codes (and
    # 500 when debug is disabled)
    app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf)

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

    # Static files
    javascripts_app = StaticJavascripts()
    static_app = StaticURLParser(config['pylons.paths']['static_files'])
    app = Cascade([static_app, javascripts_app, app])
    return app
Ejemplo n.º 30
0
def make_app(global_conf, full_stack=True, **app_conf):
    """Create a WSGI application and return it
    
    global_conf is a dict representing the Paste configuration options, the
    paste.deploy.converters should be used when parsing Paste config options
    to ensure they're treated properly.
    
    """
    # Setup the Paste CONFIG object
    CONFIG.push_process_config({'app_conf': app_conf,
                                'global_conf': global_conf})

    # Load our Pylons configuration defaults
    config = load_environment(global_conf, app_conf)
    config.init_app(global_conf, app_conf, package='web')
        
    # Load our default Pylons WSGI app and make g available
    app = pylons.wsgiapp.PylonsApp(config, helpers=web.lib.helpers,
                                   g=app_globals.Globals)
    g = app.globals
    app = ConfigMiddleware(app, {'app_conf':app_conf,
        'global_conf':global_conf})
    
    # YOUR MIDDLEWARE
    # Put your own middleware here, so that any problems are caught by the error
    # handling middleware underneath
    
    # If errror handling and exception catching will be handled by middleware
    # for multiple apps, you will want to set full_stack = False in your config
    # file so that it can catch the problems.
    if asbool(full_stack):
        # Change HTTPExceptions to HTTP responses
        app = httpexceptions.make_middleware(app, global_conf)
    
        # Error Handling
        app = ErrorHandler(app, global_conf, error_template=error_template, **config.errorware)
    
        # Display error documents for 401, 403, 404 status codes (if debug is disabled also
        # intercepts 500)
        app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf)
    
    # Establish the Registry for this application
    app = RegistryManager(app)
    
    static_app = StaticURLParser(config.paths['static_files'])
    javascripts_app = StaticJavascripts()
    app = Cascade([static_app, javascripts_app, app])
    return app