Exemplo n.º 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.
    """
    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")
Exemplo n.º 2
0
                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)

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

    # Start the scheduler
    if conf('tg.scheduler', False):
        scheduler._start_scheduler()
        log.info("Scheduler started")

def stopTurboGears():
    """Handles TurboGears tasks when the CherryPy server stops.

    Ends all open database transactions, shuts down all extensions, calls user
    provided shutdown functions and stops the scheduler.

    """
    # end all transactions and clear out the hubs to
    # help ensure proper reloading in autoreload situations
    for hub in hub_registry:
        hub.end()
    hub_registry.clear()
Exemplo n.º 3
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')
 def setUp(self):
     self.sched = _start_scheduler()