コード例 #1
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
コード例 #2
0
def make_wsgi_app():
    # BasicAuth applications
    create = AuthBasicHandler(BlogCreate, 'www', authfunc)
    update = AuthBasicHandler(BlogUpdate, 'www', authfunc)
    delete = AuthBasicHandler(BlogDelete, 'www', authfunc)

    # URL dispatching middleware
    dispatch = selector.Selector()
    dispatch.add('/', GET=BlogIndex)
    dispatch.prefix = '/article'
    dispatch.add('/add', GET=create, POST=create)
    dispatch.add('/{id:digits}', GET=BlogRead)
    dispatch.add('/{id:digits}/edit', GET=update, POST=update)
    dispatch.add('/{id:digits}/delete', GET=delete)

    # Static files
    from paste.urlparser import StaticURLParser
    static_app = StaticURLParser("my_wsgi_blog/static/")

    from paste import urlmap
    mapping = urlmap.URLMap()
    mapping['/static'] = static_app

    from paste.cascade import Cascade
    app = Cascade([mapping, dispatch])

    return app
コード例 #3
0
ファイル: middleware.py プロジェクト: aminhp93/pylons_demo
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
コード例 #4
0
ファイル: controllers.py プロジェクト: iNeft/bespin
def make_app():
    from webob import Response
    import static
    static_app = static.Cling(c.static_dir)
    if c.static_override:
        from paste.cascade import Cascade
        static_app = Cascade([static.Cling(c.static_override), static_app])

    docs_app = pathpopper_middleware(static.Cling(c.docs_dir))
    code_app = pathpopper_middleware(static.Cling(c.static_dir + "/js"), 2)

    register("^/docs/code/", code_app)
    register("^/docs/", docs_app)

    for location, directory in c.static_map.items():
        topop = 1 + location.count('/')
        more_static = pathpopper_middleware(static.Cling(directory), topop)
        register("^/%s/" % location, more_static)

    app = URLRelay(default=static_app)
    app = auth_tkt.AuthTKTMiddleware(app,
                                     c.secret,
                                     secure=c.secure_cookie,
                                     include_ip=False,
                                     httponly=c.http_only_cookie,
                                     current_domain_cookie=True,
                                     wildcard_cookie=True)
    app = db_middleware(app)

    if c.log_requests_to_stdout:
        from paste.translogger import TransLogger
        app = TransLogger(app)

    app = scriptwrapper_middleware(app)
    return app
コード例 #5
0
ファイル: middleware.py プロジェクト: dativebase/old
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
コード例 #6
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
コード例 #7
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
コード例 #8
0
ファイル: main_app.py プロジェクト: davaya/ocv
def main():
    from paste import httpserver
    from paste.cascade import Cascade
    from webob.static import DirectoryApp, FileApp

# Create a cascade that looks for static files first, then tries the webapp
    static_app = DirectoryApp("static")
    fullapp = Cascade([static_app, app])
    httpserver.serve(fullapp, host='localhost', port='8070')
コード例 #9
0
def devserver(storageModel):
    """Starts a development server with a development, sqllite based
    model.  Otherwise, gcloud compatible storage will be used."""
    from paste import httpserver
    from paste.urlparser import StaticURLParser
    from paste.cascade import Cascade
    static_server = StaticURLParser('client')
    testapp = Cascade([static_server, app])
    httpserver.serve(testapp, host='127.0.0.1', port='8080')
コード例 #10
0
    def filter_app_factory(cls, app, global_conf, prefix='', **app_conf):
        """Set-up Policy Enforcement Point to enforce access control decisions
        based on the URI path requested and/or the HTTP response code set by
        application(s) to be protected.  An AuthKit ``MultiHandler`` is setup to 
        handle the latter.  ``PEPResultHandlerMiddleware`` handles the output
        set following an access denied decision
        
        :type app: callable following WSGI interface
        :param app: next middleware application in the chain      
        :type global_conf: dict        
        :param global_conf: ``PasteDeploy`` global configuration dictionary
        :type prefix: basestring
        :param prefix: prefix for configuration items
        :type app_conf: dict        
        :param app_conf: ``PasteDeploy`` application specific configuration \
        dictionary

        """
        # Allow for static content for use with PEP result handler middleware 
        resultHandlerParamPrefix = prefix + cls.RESULT_HANDLER_PARAM_PREFIX
        resultHandlerStaticContentDirParamName = \
                                resultHandlerParamPrefix + \
                                cls.RESULT_HANDLER_STATIC_CONTENT_DIR_PARAMNAME
        
        resultHandlerStaticContentDir = app_conf.get(
                                    resultHandlerStaticContentDirParamName)
        if resultHandlerStaticContentDir is not None:    
            staticApp = StaticURLParser(resultHandlerStaticContentDir)
            app = Cascade([app, staticApp], catch=(httplib.NOT_FOUND,))

        pepPrefix = prefix + cls.PEP_PARAM_PREFIX
        pepFilter = cls.PEP_FILTER.filter_app_factory(app, 
                                                      global_conf, 
                                                      prefix=pepPrefix, 
                                                      **app_conf)
        
        # Now add the multi-handler to enable result handler to be invoked on
        # 403 forbidden status from upstream middleware 
        app = MultiHandler(pepFilter)

        resultHandlerClassName = app_conf.pop(
                                            prefix+cls.RESULT_HANDLER_PARAMNAME, 
                                            None)
        if resultHandlerClassName is None:
            resultHandler = PEPResultHandlerMiddleware
        else:
            resultHandler = importClass(resultHandlerClassName,
                                    objectType=PEPResultHandlerMiddlewareBase)
                               
        app.add_method(resultHandler.__class__.__name__,
                       resultHandler.filter_app_factory,
                       global_conf,
                       prefix=resultHandlerParamPrefix,
                       **app_conf)
        
        app.add_checker(resultHandler.__class__.__name__, 
                        Http403ForbiddenStatusHandler.intercept)
        
        return app
コード例 #11
0
    def main():
        from paste import httpserver
        from paste.cascade import Cascade
        from paste.urlparser import StaticURLParser

        assets_dir = os.path.join(os.path.dirname(__file__))
        static_app = StaticURLParser(directory=assets_dir)

        web_app = Cascade([app, static_app])
        httpserver.serve(web_app, host='localhost', port='8080')
コード例 #12
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
コード例 #13
0
ファイル: middleware.py プロジェクト: worldforge/wombat
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
コード例 #14
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
コード例 #15
0
def main():
    from paste.urlparser import StaticURLParser
    from paste.cascade import Cascade
    # FIXME: this makes the source of the
    # App downloadable; we should put css/js
    # inside of a special serving folder
    static_app = StaticURLParser(".")

    # look for css, js, html before webapp URLs
    appfull = Cascade([static_app, app])

    from paste import httpserver
    httpserver.serve(appfull)
コード例 #16
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
コード例 #17
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
コード例 #18
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
コード例 #19
0
ファイル: middleware.py プロジェクト: SpComb/myottd
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
コード例 #20
0
def make_filter_app(app, global_conf, **app_conf):
    """Create a WSGI filter and return application

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

    ``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 environment and fill conf dictionary.
    environment.load_environment(global_conf, app_conf)

    # Dispatch request to controllers.
    app = controllers.make_router(app)

    # Init request-dependant environment
    app = environment_setter(app)
    ##    app = language_detector(app)

    # Repair badly encoded query in request URL.
    app = request_query_encoding_fixer(app)

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

    #    # Handle Python exceptions
    #    if not conf['debug']:
    #        app = ErrorMiddleware(app, global_conf, **conf['errorware'])

    if conf['static_files']:
        # Serve static files
        static_app = StaticURLParser(conf['static_files_dir'])
        app = Cascade([static_app, app])

    if conf['sentry.dsn']:
        from raven import Client
        from raven.middleware import Sentry

        client = Client(
            dsn=conf.get('sentry.dsn'),
            site=conf.get('sentry.site'),
        )
        app = Sentry(app, client=client)

    return app
コード例 #21
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.
    
    """
    load_environment(global_conf, app_conf)

    # Pull the other engine and put a new one up first
    config.template_engines.pop()
    kidopts = {'kid.assume_encoding': 'utf-8', 'kid.encoding': 'utf-8'}
    pylons.config.add_template_engine('kid', 'projectname.kidtemplates',
                                      kidopts)

    # Load our default Pylons WSGI app and make g available
    app = pylons.wsgiapp.PylonsApp(helpers=projectname.lib.helpers,
                                   g=app_globals.Globals)
    app = ConfigMiddleware(app, config._current_obj())

    # 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['pylons.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['pylons.paths']['static_files'])
    javascripts_app = StaticJavascripts()
    app = Cascade([static_app, javascripts_app, app])
    return app
コード例 #22
0
def make_app(mode):
    service_app = RouterApp(mode)

    service_app.add_route("/user/signup", 'UserApp', 'signup')
    service_app.add_route("/user/login", 'UserApp', 'login')
    service_app.add_route("/user/tagitem", 'UserApp', 'tag_item')
    service_app.add_route("/user/detagitem", 'UserApp', 'detag_item')
    service_app.add_route("/tag/addbyname", 'TagApp', 'add_by_name')
    service_app.add_route("/tag/getbyitem", 'TagApp', 'get_by_item')
    service_app.add_route("/tag/gettop10", 'TagApp', 'get_top10')
    service_app.add_route("/tag/searchbyprefix", 'TagApp', 'search_by_prefix')
    service_app.add_route("/paper/addbibtex", 'PaperApp', 'add_by_bibtex')
    service_app.add_route("/paper/getbyid", 'PaperApp', 'get_by_id')
    service_app.add_route("/paper/getbytag", 'PaperApp', 'get_by_tag')
    service_app.add_route("/paper/gettop10", 'PaperApp', 'get_top10')

    static_app = StaticURLParser('../www/')
    cascade_app = [service_app,static_app]

    return Cascade(cascade_app)
コード例 #23
0
ファイル: wsgiapp.py プロジェクト: decause/moksha
 def __init__(self,
              global_conf={},
              template_dirs=None,
              interactive=False,
              docs_dir=None,
              full_stack=True):
     if isinstance(template_dirs, basestring):
         template_dirs = template_dirs.split()
     template_dirs = template_dirs or []
     template_dirs.append(
         resource_filename('moksha.widgetbrowser', 'templates'))
     self.loader = TemplateLoader(template_dirs)
     self.interactive = asbool(interactive)
     if self.interactive:
         self.http_repl = repl.WidgetReplApp(globals(), weakref.proxy(self))
         self.context = self.http_repl.repl.locals
     else:
         self.context = None
         self.http_repl = exc.HTTPForbidden("Interactive mode is disabled")
     if docs_dir:
         from paste.cascade import Cascade
         dest_dir = os.path.abspath(os.path.join(docs_dir))
         #log.info('Building docs...')
         #try:
         #    util.build_docs(docs_dir, dest_dir)
         #except Exception, e:
         #    log.warning('Skipping building docs: %s' % str(e))
         self.built_docs = dest_dir
         self.app = Cascade([self.docs_app, self.app])
     if asbool(full_stack):
         self.app = twc.make_middleware(
             self.app, {
                 'toscawidgets.framework.default_view': 'genshi',
             },
             stack_registry=True)
     self._default_controllers = dict(demo=self.show_demo,
                                      index=self.show_index,
                                      template=self.show_template,
                                      parameters=self.show_parameters,
                                      source=self.show_source,
                                      demo_source=self.show_demo_source)
コード例 #24
0
ファイル: middlewares.py プロジェクト: plastic-data/suqui1
def wrap_app(app):
    """Encapsulate main WSGI application within WSGI middlewares."""
    # Initialize request-dependant environment.
    app = environment_setter(app)
    app = language_detector(app)

    # Repair badly encoded query in request URL.
    app = request_query_encoding_fixer(app)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)

    # Handle Python exceptions
    if not conf['debug']:
        app = ErrorMiddleware(app, conf['global_conf'], **conf['errorware'])

    if conf['static_files']:
        # Serve static files
        static_app = StaticURLParser(conf['static_files_dir'])
        app = Cascade([static_app, app])

    return app
コード例 #25
0
def make_app(global_conf, **app_conf):
    global app, log

    logging.config.fileConfig(global_conf['__file__'])
    log = logging.getLogger('solder')

    import solder.logger

    app = wrap = Solder(global_conf, **app_conf)

    from beaker.middleware import SessionMiddleware
    wrap = SessionMiddleware(wrap, app.config)

    from beaker.middleware import CacheMiddleware
    wrap = CacheMiddleware(wrap, app.config)

    from routes.middleware import RoutesMiddleware
    wrap = RoutesMiddleware(wrap, app)

    if False and app.debug:
        from repoze.profile.profiler import AccumulatingProfileMiddleware
        wrap = AccumulatingProfileMiddleware(wrap,
                                             log_filename='./logs/profile.log',
                                             discard_first_request=True,
                                             flush_at_shutdown=True,
                                             path='/_profile_')

    from weberror.evalexception import make_general_exception
    wrap = make_general_exception(wrap, global_conf,
                                  asbool(app.config['interactive']))

    from paste.fileapp import DirectoryApp
    public = DirectoryApp('./solder/public')

    from paste.cascade import Cascade
    wrap = Cascade([public, wrap], [403, 404])

    return wrap
コード例 #26
0
    def __init__(self, app, global_conf, **local_conf):
        '''Extend SignInterface to include config and set-up for Genshi
        object
        
        @type app: callable following WSGI interface
        @param app: next middleware application in the chain      
        @type global_conf: dict        
        @param global_conf: PasteDeploy global configuration dictionary
        enables other global configuration parameters to be filtered out
        @type local_conf: dict        
        @param local_conf: PasteDeploy application specific configuration 
        dictionary
        '''
        super(GenshiSigninTemplate, self).__init__(app, global_conf,
                                                   **local_conf)

        self.__loader = TemplateLoader(self.templateRootDir, auto_reload=True)

        self.title = "Enter your OpenID to Sign in"
        self.xml = ''
        self.headExtras = ''
        self.loginStatus = True
        self.loggedIn = False

        # TODO: handle session object scope
        self.session = {'username': ''}

        if self.staticContentRootDir is not None:
            staticApp = StaticURLParser(self.staticContentRootDir)
            appList = [staticApp]

            # Check next app is set - if it is, add to the Cascade - Nb.
            # THIS middleware may behave as an app in which case there is no
            # next app in the chain
            if self._app is not None:
                appList += [self._app]

            self._app = Cascade(appList, catch=(404, 401))
コード例 #27
0
ファイル: middleware.py プロジェクト: freelizhun/pycloud
def generic_make_app(make_map_function, controllers_module, root_path,
                     global_conf, **app_conf):
    print "-------------------------------------------------------"

    # Configure the Pylons environment.
    from pycloud.pycloud.pylons.config.environment import load_environment
    config = load_environment(make_map_function, root_path, global_conf,
                              app_conf)

    # Create the base app, and wrap it in middleware.
    app = CloudletApp(controllers_module, config)
    app = RoutesMiddleware(app, config["routes.map"])
    app = SessionMiddleware(app, config)
    app = RegistryManager(app, streaming=True)

    # Create the sub-app to serve static files.
    static_app = StaticURLParser(config['pylons.paths']['static_files'])

    # Set up the order apps are resolved (static and the main one).
    app = Cascade([static_app, app])

    print "-------------------------------------------------------"
    app.config = config
    return app
コード例 #28
0
 def add_static_file_middleware(self, app):
     static_app = StaticURLParser(config['pylons.paths']['static_files'])
     app = Cascade([static_app, app])
     return app
コード例 #29
0
ファイル: middleware.py プロジェクト: znanl/reddit
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)
    g = config['pylons.g']

    # The Pylons WSGI app
    app = RedditApp()
    app = RoutesMiddleware(app, config["routes.map"])

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

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

    app = LimitUploadSize(app)

    profile_directory = g.config.get('profile_directory')
    if profile_directory:
        app = ProfilingMiddleware(app, profile_directory)

    app = DomainListingMiddleware(app)
    app = SubredditMiddleware(app)
    app = ExtensionMiddleware(app)
    app = DomainMiddleware(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)
        app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf)

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

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

    if config['r2.plugins'] and g.config['uncompressedJS']:
        plugin_static_apps = Cascade([
            StaticURLParser(plugin.static_dir)
            for plugin in config['r2.plugins']
        ])
        static_cascade.insert(0, plugin_static_apps)
    app = Cascade(static_cascade)

    app = FullPathMiddleware(app)

    if not g.config['uncompressedJS'] and g.config['debug']:
        static_fallback = StaticTestMiddleware(static_app,
                                               g.config['static_path'],
                                               g.config['static_domain'])
        app = Cascade([static_fallback, app])

    app = SafetyMiddleware(app)

    return app
コード例 #30
0
ファイル: middleware.py プロジェクト: AnonOnWarpath/adhocracy
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).

    """

    debug = asbool(config['debug'])

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

    #app = make_profile_middleware(app, config, log_filename='profile.log.tmp')

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
    app = setup_auth(app, config)
    app = setup_discriminator(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 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):
        cache_age = int(config.get('adhocracy.static.age', 7200))
        # Serve static files
        overlay_app = StaticURLParser(
            get_site_path('static'),
            cache_max_age=None if debug else cache_age)
        static_app = StaticURLParser(
            config['pylons.paths']['static_files'],
            cache_max_age=None if debug else cache_age)
        app = Cascade([overlay_app, static_app, app])

    return app
コード例 #31
0
ファイル: cascade.py プロジェクト: hep-gc/repoman
 def __init__(self, app, applications, catch=(404,)):
     self.app = app
     Cascade.__init__(self, applications, catch)
コード例 #32
0
ファイル: cascade.py プロジェクト: hep-gc/repoman
 def __call__(self, environ, start_response):
     if environ.get("BYPASS_CASCADE"):
         return self.app(environ, start_response)
     else:
         return Cascade.__call__(self, environ, start_response)