Example #1
0
def startTurboGears():
    """Handles TurboGears tasks when the CherryPy server starts.

    This adds the "tg_js" configuration to make MochiKit accessible.
    It also turns on stdlib logging when in development mode.

    """
    # Set up old-style logging
    cherrypy.config.environments['development'][
        'log_debug_info_filter.on'] = False

    if not config.get('tg.new_style_logging'):
        if config.get('server.log_to_screen'):
            setuplog = logging.getLogger()
            setuplog.setLevel(logging.DEBUG)
            fmt = logging.Formatter(
                "%(asctime)s %(name)s %(levelname)s %(message)s")
            handler = logging.StreamHandler(sys.stdout)
            handler.setLevel(logging.DEBUG)
            handler.setFormatter(fmt)
            setuplog.addHandler(handler)

        logfile = config.get('server.log_file')
        if logfile:
            setuplog = logging.getLogger('turbogears.access')
            setuplog.propagate = 0
            fmt = logging.Formatter("%(message)s")
            handler = logging.FileHandler(logfile)
            handler.setLevel(logging.INFO)
            handler.setFormatter(fmt)
            setuplog.addHandler(handler)

    # Add static filters
    resource_filename = pkg_resources.resource_filename
    config.update({'/tg_static': {
            'static_filter.on': True,
            'static_filter.dir':
                os.path.abspath(resource_filename(__name__, 'static')),
            'log_debug_info_filter.on': False,
        }})
    config.update({'/tg_js': {
            'static_filter.on': True,
            'static_filter.dir':
                os.path.abspath(resource_filename(__name__, 'static/js')),
            'log_debug_info_filter.on': False,
        }})
    mochikit_version = config.get(
        'tg.mochikit_version', config.get('tg_mochikit.version', '1.3'))
    mochikit_suffix = '_'.join(mochikit_version.split('.', 2)[:2])
    mochikit_file = os.path.abspath(resource_filename(
        __name__, 'static/js/MochiKit_%s.js' % mochikit_suffix))
    if os.path.exists(mochikit_file):
        for path in ('/tg_static/js/MochiKit.js', '/tg_js/MochiKit.js',
                '/tg_widgets/turbogears/js/MochiKit.js'):
            config.update({path: {
                'static_filter.on': True,
                'static_filter.file': mochikit_file,
            }})
    else:
        log.warning("MochiKit version %s not available" % mochikit_version)
    # Add decoding filter
    if config.get('decoding_filter.on', path='/') is None:
        config.update({'/': {
            'decoding_filter.on': True,
            'decoding_filter.encoding': config.get('kid.encoding', 'utf8')
        }})

    # Initialize template engines and load base templates
    view.load_engines()
    view.loadBaseTemplates()

    # Add request filters
    global webpath
    webpath = config.get('server.webpath') or ''

    if getattr(cherrypy, 'root', None):
        if not hasattr(cherrypy.root, '_cp_filters'):
            cherrypy.root._cp_filters = []
        cherrypy.root._cp_filters.extend([VirtualPathFilter(webpath),
            EndTransactionsFilter(), NestedVariablesFilter()])

    webpath = webpath.lstrip('/')
    if webpath and not webpath.endswith('/'):
        webpath += '/'

    # Register server with Bonjour framework
    bonjoursetting = config.get('tg.bonjour', None)
    if bonjoursetting or config.get('server.environment') == 'development':
        start_bonjour(bonjoursetting)

    # Bind metadata for SQLAlchemy
    if config.get("sqlalchemy.dburi"):
        database.get_engine()

    # Start all TurboGears extensions
    extensions = pkg_resources.iter_entry_points('turbogears.extensions')
    for entrypoint in extensions:
        ext = entrypoint.load()
        if hasattr(ext, 'start_extension'):
            ext.start_extension()

    # Call registered startup functions
    for item in call_on_startup:
        item()

    # Start the scheduler
    if config.get('tg.scheduler', False):
        scheduler._start_scheduler()
        log.info('Scheduler started')
Example #2
0
def startTurboGears():
    """Handles TurboGears tasks when the CherryPy server starts.

    This adds the "tg_js" configuration to make MochiKit accessible.
    It also turns on stdlib logging when in development mode.
    """
    config.update({"/tg_static":
            {
            "static_filter.on": True,
            "static_filter.dir":
                os.path.abspath(pkg_resources.resource_filename(__name__, "static")),
            'log_debug_info_filter.on' : False,
            }
        })
    config.update({"/tg_js" :
            {
            "static_filter.on" : True,
            "static_filter.dir" :
                os.path.abspath(pkg_resources.resource_filename(__name__, "static/js")),
            'log_debug_info_filter.on' : False,
            }
        })
    cherrypy.config.environments['development']['log_debug_info_filter.on'] = False
    
    if config.get("decoding_filter.on", path="/") is None:
        config.update({"/": {
            "decoding_filter.on" : True,
            "decoding_filter.encoding" : config.get(
                                        "kid.encoding", "utf8")
        }})
        
    view.load_engines()
    view.loadBaseTemplates()
    global webpath
    webpath = config.get("server.webpath", "")

    if hasattr(cherrypy, "root") and cherrypy.root:
        if not hasattr(cherrypy.root, "_cp_filters"):
            cherrypy.root._cp_filters= []
        morefilters = [EndTransactionsFilter(),
                       NestedVariablesFilter()]
        if webpath:
            morefilters.insert(0, VirtualPathFilter())
        cherrypy.root._cp_filters.extend(morefilters)

    if webpath.startswith("/"):
        webpath = webpath[1:]
    if webpath and not webpath.endswith("/"):
        webpath = webpath + "/"
    isdev = config.get('server.environment') == 'development'
    if not config.get("tg.new_style_logging"):
        if config.get('server.log_to_screen'):
            setuplog = logging.getLogger()
            setuplog.setLevel(logging.DEBUG)
            fmt = logging.Formatter("%(asctime)s %(name)s "
                                    "%(levelname)s %(message)s")
            handler = logging.StreamHandler(sys.stdout)
            handler.setLevel(logging.DEBUG)
            handler.setFormatter(fmt)
            setuplog.addHandler(handler)
        
        logfile = config.get("server.log_file")
        if logfile:
            setuplog = logging.getLogger("turbogears.access")
            setuplog.propagate = 0
            fmt = logging.Formatter("%(message)s")
            handler = logging.FileHandler(logfile)
            handler.setLevel(logging.INFO)
            handler.setFormatter(fmt)
            setuplog.addHandler(handler)

    bonjoursetting = config.get("tg.bonjour", None)
    if bonjoursetting or isdev:
        start_bonjour(bonjoursetting)
    
    if config.get("sqlalchemy.dburi"):
        database.bind_meta_data()

    # Start all TurboGears extensions
    extensions= pkg_resources.iter_entry_points( "turbogears.extensions" )
    for entrypoint in extensions:
        ext= entrypoint.load()
        if hasattr(ext, "start_extension"):
            ext.start_extension()
    
    for item in call_on_startup:
        item()
        
    if config.get("tg.scheduler", False):
        scheduler._start_scheduler()
        log.info("Scheduler started")
Example #3
0
def startTurboGears():
    """Handles TurboGears tasks when the CherryPy server starts.

    This performs the following initialization tasks (in given order):

    * Turns off CherryPy's logging filter when in development mode
    * If logging is not already set up, turns on old-style stdlib logging.
    * Adds a static filter for TurboGears's static files (URL '/tg_static').
    * Adds a static filter for TurboGears's JavaScript files (URL '/tg_js').
    * Loads the template engines and the base templates.
    * Adds the CherryPy request filters to the root controller.
    * Adds the decoding filter to the root URL ('/') if enabled in the
      configuration.
    * Registers the server with the Bonjour framework, if available.
    * Calls 'turbogears.database.bind_metadata' when using SQLAlchemy.
    * Loads all turbogears.extensions entry points and calls their
      'start_extension' method.
    * Calls the callables registered in 'turbogears.call_on_startup'.
    * Starts the TurboGears scheduler.

    """
    global webpath
    conf = config.get
    rfn = pkg_resources.resource_filename

    cherrypy.config.environments['development'][
        'log_debug_info_filter.on'] = False

    # XXX: obsolete --> to be removed
    # Set up old-style logging
    if not conf('tg.new_style_logging', False):
        if conf('server.log_to_screen'):
            setuplog = logging.getLogger()
            setuplog.setLevel(logging.DEBUG)
            fmt = logging.Formatter(
                "%(asctime)s %(name)s %(levelname)s %(message)s")
            handler = logging.StreamHandler(sys.stdout)
            handler.setLevel(logging.DEBUG)
            handler.setFormatter(fmt)
            setuplog.addHandler(handler)

        logfile = conf('server.log_file')
        if logfile:
            setuplog = logging.getLogger('turbogears.access')
            setuplog.propagate = 0
            fmt = logging.Formatter("%(message)s")
            handler = logging.FileHandler(logfile)
            handler.setLevel(logging.INFO)
            handler.setFormatter(fmt)
            setuplog.addHandler(handler)

    # Add static filters
    config.update({'/tg_static': {
        'static_filter.on': True,
        'static_filter.dir': abspath(rfn(__name__, 'static')),
        'log_debug_info_filter.on': False,
    }})
    config.update({'/tg_js': {
        'static_filter.on': True,
        'static_filter.dir': abspath(rfn(__name__, 'static/js')),
        'log_debug_info_filter.on': False,
    }})
    # Add decoding filter
    if conf('decoding_filter.on', path='/') is None:
        config.update({'/': {
            'decoding_filter.on': True,
            'decoding_filter.encoding': conf('kid.encoding', 'utf8')
        }})

    # Initialize template engines and load base templates
    view.load_engines()
    view.loadBaseTemplates()

    # Add request filters
    webpath = conf('server.webpath') or ''

    if getattr(cherrypy, 'root', None):
        if not hasattr(cherrypy.root, '_cp_filters'):
            cherrypy.root._cp_filters = []
        extra_filters = [
            VirtualPathFilter(webpath),
            EndTransactionsFilter(),
            NestedVariablesFilter(),
            SafeMultipartFilter()
        ]
        # Do not add filters twice which are already present
        for cp_filter in cherrypy.root._cp_filters[:]:
            for candidate in extra_filters:
                if candidate.__class__ == cp_filter.__class__:
                    extra_filters.remove(candidate)
                    break
        cherrypy.root._cp_filters.extend(extra_filters)

    # Monkey patch CherryPy Decoding filter: injects our replacement filter
    # MonkeyDecodingFilter into the CherryPy filter chain
    decoding_filter = MonkeyDecodingFilter()
    for index, active_filter in enumerate(
            cherrypy.filters._filterhooks.get('before_main', [])):
        if active_filter.im_class == \
                cherrypy.filters.decodingfilter.DecodingFilter:
            cherrypy.filters._filterhooks['before_main'].pop(index)
            if conf('decoding_filter.on', False, path='/'):
                log.info("Request decoding filter activated.")
                cherrypy.filters._filterhooks['before_main'].insert(
                        index, decoding_filter.before_main)


    webpath = webpath.lstrip('/')
    if webpath and not webpath.endswith('/'):
        webpath += '/'

    # Register server with Bonjour framework
    bonjoursetting = conf('tg.bonjour', None)
    if bonjoursetting or conf('server.environment') == 'development':
        start_bonjour(bonjoursetting)

    # Bind metadata for SQLAlchemy
    if conf('sqlalchemy.dburi'):
        database.bind_metadata()

    # Start all TurboGears extensions
    extensions = pkg_resources.iter_entry_points('turbogears.extensions')
    for entrypoint in extensions:
        # We try to load the extension and run its 'start_extension'
        # method ,if present. If either fails, we simply log the exception and
        # continue, because a) when the autoreloader is active, unhandled
        # exceptions in the startup phase will not stop the server and
        # b) faulty extensions (which may be from a different package)
        # should not crash the server.
        try:
            ext = entrypoint.load()
        except Exception, e:
            log.exception("Error loading TurboGears extension plugin '%s': %s",
                entrypoint, e)
            continue
        if hasattr(ext, 'start_extension'):
            try:
                ext.start_extension()
            except Exception, e:
                log.exception("Error starting TurboGears extension '%s': %s",
                    entrypoint, e)