root/galaxy-central/lib/galaxy/webapps/reports/buildapp.py @ 3

リビジョン 2, 7.9 KB (コミッタ: hatakeyama, 14 年 前)

import galaxy-central

行番号 
1"""
2Provides factory methods to assemble the Galaxy web application
3"""
4
5import logging, atexit
6import os, os.path, sys
7
8from inspect import isclass
9
10from paste.request import parse_formvars
11from paste.util import import_string
12from paste import httpexceptions
13from paste.deploy.converters import asbool
14import pkg_resources
15
16log = logging.getLogger( __name__ )
17
18import config
19import galaxy.model
20import galaxy.model.mapping
21import galaxy.web.framework
22
23def add_controllers( webapp, app ):
24    """
25    Search for controllers in the 'galaxy.webapps.controllers' module and add
26    them to the webapp.
27    """
28    from galaxy.web.base.controller import BaseController
29    from galaxy.web.base.controller import ControllerUnavailable
30    import galaxy.webapps.reports.controllers
31    controller_dir = galaxy.webapps.reports.controllers.__path__[0]
32    for fname in os.listdir( controller_dir ):
33        if not fname.startswith( "_" ) and fname.endswith( ".py" ):
34            name = fname[:-3]
35            module_name = "galaxy.webapps.reports.controllers." + name
36            module = __import__( module_name )
37            for comp in module_name.split( "." )[1:]:
38                module = getattr( module, comp )
39            # Look for a controller inside the modules
40            for key in dir( module ):
41                T = getattr( module, key )
42                if isclass( T ) and T is not BaseController and issubclass( T, BaseController ):
43                    webapp.add_controller( name, T( app ) )
44
45def app_factory( global_conf, **kwargs ):
46    """Return a wsgi application serving the root object"""
47    # Create the Galaxy application unless passed in
48    if 'app' in kwargs:
49        app = kwargs.pop( 'app' )
50    else:
51        from galaxy.webapps.reports.app import UniverseApplication
52        app = UniverseApplication( global_conf = global_conf, **kwargs )
53    atexit.register( app.shutdown )
54    # Create the universe WSGI application
55    webapp = galaxy.web.framework.WebApplication( app, session_cookie='galaxyreportssession' )
56    add_controllers( webapp, app )
57    # These two routes handle our simple needs at the moment
58    webapp.add_route( '/:controller/:action', controller="root", action='index' )
59    webapp.add_route( '/:action', controller='root', action='index' )
60    webapp.finalize_config()
61    # Wrap the webapp in some useful middleware
62    if kwargs.get( 'middleware', True ):
63        webapp = wrap_in_middleware( webapp, global_conf, **kwargs )
64    if kwargs.get( 'static_enabled', True ):
65        webapp = wrap_in_static( webapp, global_conf, **kwargs )
66    # Close any pooled database connections before forking
67    try:
68        galaxy.model.mapping.metadata.engine.connection_provider._pool.dispose()
69    except:
70        pass
71    # Return
72    return webapp
73   
74def wrap_in_middleware( app, global_conf, **local_conf ):
75    """Based on the configuration wrap `app` in a set of common and useful middleware."""
76    # Merge the global and local configurations
77    conf = global_conf.copy()
78    conf.update(local_conf)
79    debug = asbool( conf.get( 'debug', False ) )
80    # First put into place httpexceptions, which must be most closely
81    # wrapped around the application (it can interact poorly with
82    # other middleware):
83    app = httpexceptions.make_middleware( app, conf )
84    log.debug( "Enabling 'httpexceptions' middleware" )
85    # The recursive middleware allows for including requests in other
86    # requests or forwarding of requests, all on the server side.
87    if asbool(conf.get('use_recursive', True)):
88        from paste import recursive
89        app = recursive.RecursiveMiddleware( app, conf )
90        log.debug( "Enabling 'recursive' middleware" )
91    # Various debug middleware that can only be turned on if the debug
92    # flag is set, either because they are insecure or greatly hurt
93    # performance
94    if debug:
95        # Middleware to check for WSGI compliance
96        if asbool( conf.get( 'use_lint', True ) ):
97            from paste import lint
98            app = lint.make_middleware( app, conf )
99            log.debug( "Enabling 'lint' middleware" )
100        # Middleware to run the python profiler on each request
101        if asbool( conf.get( 'use_profile', False ) ):
102            import profile
103            app = profile.ProfileMiddleware( app, conf )
104            log.debug( "Enabling 'profile' middleware" )
105        # Middleware that intercepts print statements and shows them on the
106        # returned page
107        if asbool( conf.get( 'use_printdebug', True ) ):
108            from paste.debug import prints
109            app = prints.PrintDebugMiddleware( app, conf )
110            log.debug( "Enabling 'print debug' middleware" )
111    if debug and asbool( conf.get( 'use_interactive', False ) ):
112        # Interactive exception debugging, scary dangerous if publicly
113        # accessible, if not enabled we'll use the regular error printing
114        # middleware.
115        pkg_resources.require( "WebError" )
116        from weberror import evalexception
117        app = evalexception.EvalException( app, conf,
118                                           templating_formatters=build_template_error_formatters() )
119        log.debug( "Enabling 'eval exceptions' middleware" )
120    else:
121        # Not in interactive debug mode, just use the regular error middleware
122        from paste.exceptions import errormiddleware
123        app = errormiddleware.ErrorMiddleware( app, conf )
124        log.debug( "Enabling 'error' middleware" )
125    # Transaction logging (apache access.log style)
126    if asbool( conf.get( 'use_translogger', True ) ):
127        from paste.translogger import TransLogger
128        app = TransLogger( app )
129        log.debug( "Enabling 'trans logger' middleware" )
130    # Config middleware just stores the paste config along with the request,
131    # not sure we need this but useful
132    from paste.deploy.config import ConfigMiddleware
133    app = ConfigMiddleware( app, conf )
134    log.debug( "Enabling 'config' middleware" )
135    # X-Forwarded-Host handling
136    from galaxy.web.framework.middleware.xforwardedhost import XForwardedHostMiddleware
137    app = XForwardedHostMiddleware( app )
138    log.debug( "Enabling 'x-forwarded-host' middleware" )
139    return app
140   
141def wrap_in_static( app, global_conf, **local_conf ):
142    from paste.urlmap import URLMap
143    from galaxy.web.framework.middleware.static import CacheableStaticURLParser as Static
144    urlmap = URLMap()
145    # Merge the global and local configurations
146    conf = global_conf.copy()
147    conf.update(local_conf)
148    # Get cache time in seconds
149    cache_time = conf.get( "static_cache_time", None )
150    if cache_time is not None:
151        cache_time = int( cache_time )
152    # Send to dynamic app by default
153    urlmap["/"] = app
154    # Define static mappings from config
155    urlmap["/static"] = Static( conf.get( "static_dir" ), cache_time )
156    urlmap["/images"] = Static( conf.get( "static_images_dir" ), cache_time )
157    urlmap["/static/scripts"] = Static( conf.get( "static_scripts_dir" ), cache_time )
158    urlmap["/static/style"] = Static( conf.get( "static_style_dir" ), cache_time )
159    urlmap["/favicon.ico"] = Static( conf.get( "static_favicon_dir" ), cache_time )
160    # URL mapper becomes the root webapp
161    return urlmap
162   
163def build_template_error_formatters():
164    """
165    Build a list of template error formatters for WebError. When an error
166    occurs, WebError pass the exception to each function in this list until
167    one returns a value, which will be displayed on the error page.
168    """
169    formatters = []
170    # Formatter for mako
171    import mako.exceptions
172    def mako_html_data( exc_value ):
173        if isinstance( exc_value, ( mako.exceptions.CompileException, mako.exceptions.SyntaxException ) ):
174            return mako.exceptions.html_error_template().render( full=False, css=False )
175        if isinstance( exc_value, AttributeError ) and exc_value.args[0].startswith( "'Undefined' object has no attribute" ):
176            return mako.exceptions.html_error_template().render( full=False, css=False )
177    formatters.append( mako_html_data )
178    return formatters
Note: リポジトリブラウザについてのヘルプは TracBrowser を参照してください。