Exemple #1
0
def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    config = PylonsConfig()

    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(root, 'public'),
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='desio', paths=paths)

    config['routes.map'] = make_map(config)
    config['pylons.app_globals'] = app_globals.Globals(config)
    config['pylons.h'] = desio.lib.helpers
    config['pylons.strict_tmpl_context'] = False

    config['beaker.session.cookie_expires'] = None

    # Setup cache object as early as possible
    import pylons
    pylons.cache._push_object(config['pylons.app_globals'].cache)

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8',
        default_filters=['escape'],
        imports=['from webhelpers.html import escape'])

    # Setup the SQLAlchemy database engine
    config['pylons.app_globals'].sa_default_engine = engine_from_config(
        config, 'sqlalchemy.default.', proxy=TimerProxy())
    init_model(config['pylons.app_globals'].sa_default_engine)

    config['pylons.errorware']['smtp_username'] = config.get('smtp_username')
    config['pylons.errorware']['smtp_password'] = config.get('smtp_password')
    config['pylons.errorware']['smtp_use_tls'] = config.get('smtp_use_tls')
    config['pylons.errorware']['smtp_port'] = config.get('smtp_port')

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    fs.setup_directories(config)
    setup_turbomail(config)

    return config
Exemple #2
0
def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    config = PylonsConfig()
    
    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(root, 'public'),
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='desio', paths=paths)

    config['routes.map'] = make_map(config)
    config['pylons.app_globals'] = app_globals.Globals(config)
    config['pylons.h'] = desio.lib.helpers
    config['pylons.strict_tmpl_context'] = False
    
    config['beaker.session.cookie_expires'] = None
    
    # Setup cache object as early as possible
    import pylons
    pylons.cache._push_object(config['pylons.app_globals'].cache)
    

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8', default_filters=['escape'],
        imports=['from webhelpers.html import escape'])

    # Setup the SQLAlchemy database engine
    config['pylons.app_globals'].sa_default_engine = engine_from_config(config, 'sqlalchemy.default.', proxy=TimerProxy())
    init_model(config['pylons.app_globals'].sa_default_engine)
    
    config['pylons.errorware']['smtp_username'] = config.get('smtp_username')
    config['pylons.errorware']['smtp_password'] = config.get('smtp_password')
    config['pylons.errorware']['smtp_use_tls'] = config.get('smtp_use_tls')
    config['pylons.errorware']['smtp_port'] = config.get('smtp_port')
    
    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    fs.setup_directories(config)
    setup_turbomail(config)
    
    return config
Exemple #3
0
def load_environment(global_conf, app_conf, with_db=True):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    # Pylons paths
    conf_copy = global_conf.copy()
    conf_copy.update(app_conf)
    site_templates = create_site_subdirectory('templates', app_conf=conf_copy)
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    client_containing = app_conf.get('adhocracy.client_location')
    if client_containing:
        client_root = os.path.join(client_containing, 'adhocracy_client')
        sys.path.insert(0, client_containing)
        import adhocracy_client.static
        sys.modules['adhocracy.static'] = adhocracy_client.static
    else:
        client_root = root
    import adhocracy.static
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(client_root, 'static'),
                 templates=[site_templates,
                            os.path.join(client_root, 'templates')])

    # Initialize config with the basic options
    config = PylonsConfig()

    config.init_app(global_conf, app_conf, package='adhocracy', paths=paths)

    config['routes.map'] = make_map(config)
    config['pylons.app_globals'] = app_globals.Globals(config)
    config['pylons.h'] = adhocracy.lib.helpers

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8', default_filters=['escape'],
        imports=['from markupsafe import escape'])

    config['pylons.strict_tmpl_context'] = False

    # Setup the SQLAlchemy database engine
    engineOpts = {}
    if asbool(config.get('adhocracy.debug.sql', False)):
        engineOpts['connectionproxy'] = TimerProxy()

    engine = engine_from_config(config, 'sqlalchemy.', **engineOpts)
    init_model(engine)

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    init_site(config)
    if with_db:
        init_search()
    init_democracy()
    RQConfig.setup_from_config(config)

    return config
Exemple #4
0
def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    config = PylonsConfig()
    
    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(root, 'public'),
                 templates=[os.path.join(root, 'templates')])

    # import our private.ini that holds keys, etc
    imp = global_conf.get('import')
    if imp:
        cp = ConfigParser()
        cp.read(imp)
        global_conf.update(cp.defaults())
        if cp.has_section('APP'):
            app_conf.update(cp.items('APP'))

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='linkdrop', paths=paths)
    config['routes.map'] = make_map(config)
    config['pylons.app_globals'] = app_globals.Globals(config)

    import linkdrop.lib.helpers as h
    config['pylons.h'] = h
    
    # Setup cache object as early as possible
    import pylons
    pylons.cache._push_object(config['pylons.app_globals'].cache)

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8', default_filters=['escape'],
        imports=['from webhelpers.html import escape'])

    # Setup the SQLAlchemy database engine
    engine = engine_from_config(config, 'sqlalchemy.')
    init_model(engine)

    # sqlalchemy auto migration
    if asbool(config.get('migrate.auto')):
        try:
            # managed upgrades
            cschema = schema.ControlledSchema.create(engine, config['migrate.repository'])
            cschema.update_db_from_model(meta.Base.metadata)
        except exceptions.InvalidRepositoryError, e:
            # unmanaged upgrades
            diff = schemadiff.getDiffOfModelAgainstDatabase(
                meta.Base.metadata, engine, excludeTables=None)
            genmodel.ModelGenerator(diff).applyModel()
Exemple #5
0
def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    config = PylonsConfig()

    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(
        root=root,
        controllers=os.path.join(root, 'controllers'),
        data=os.path.join(root, 'data'),
        static_files=os.path.join(root, 'public'),
        templates=os.path.join(root, 'templates'),
    )

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='muse', paths=paths)
    config['routes.map'] = make_map(config)
    config['pylons.app_globals'] = app_globals.Globals(config)
    config['pylons.h'] = muse.lib.helpers

    # Setup cache object as early as possible
    pylons.cache._push_object(config['pylons.app_globals'].cache)
    # Setup cache options dict to pass to @cache.beaker_cache.
    config['cache_options'] = {
        'query_args': True,
        'expire': config.get('cache_expire', 3600),
        'invalidate_on_startup': True
    }
    config['cache_options_nonpage'] = {
        'expire': config.get('cache_expire', 3600),
        'invalidate_on_startup': True
    }
    # Setup SQLAlchemy
    config['pylons.app_globals'].sa_engine = engine_from_config(config,
        'sqlalchemy.'
    )
    model.init_model(config['pylons.app_globals'].sa_engine)
	# Create tables if they don't already exist.
	model.metadata.create_all(bind=model.meta.engine)
def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(root, 'public'),
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    if is_pylons_0:
        config = pylons_config
    else:
        config = PylonsConfig()
    config.init_app(global_conf, app_conf, package='fts3rest', paths=paths)

    config['routes.map'] = make_map(config)
    config['pylons.app_globals'] = app_globals.Globals(config)
    config['pylons.h'] = fts3rest.lib.helpers

    # Setup cache object as early as possible
    import pylons
    pylons.cache._push_object(config['pylons.app_globals'].cache)

    # If fts3.config is set, load configuration from there
    fts3_config_file = config.get('fts3.config')
    if fts3_config_file:
        fts3cfg = fts3_config.fts3_config_load(fts3_config_file)
        # Let the database be overriden by fts3rest.ini
        if 'sqlalchemy.url' in config and 'sqlalchemy.url' in fts3cfg:
            del fts3cfg['sqlalchemy.url']
        config.update(fts3cfg)

    # Setup the SQLAlchemy database engine
    engine = engine_from_config(config, 'sqlalchemy.', pool_recycle = 7200)
    init_model(engine)

    # Mako templating
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
    )

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    return config
Exemple #7
0
def load_environment(global_conf,
                     app_conf,
                     initial=False,
                     test_env=None,
                     test_index=None):
    """
    Configure the Pylons environment via the ``pylons.config``
    object
    """
    config = PylonsConfig()

    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(root, 'public'),
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='kallithea', paths=paths)

    # store some globals into kallithea
    kallithea.CELERY_ON = str2bool(config['app_conf'].get('use_celery'))
    kallithea.CELERY_EAGER = str2bool(
        config['app_conf'].get('celery.always.eager'))

    config['routes.map'] = make_map(config)
    config['pylons.app_globals'] = app_globals.Globals(config)
    config['pylons.h'] = helpers
    kallithea.CONFIG = config

    load_rcextensions(root_path=config['here'])

    # Setup cache object as early as possible
    import pylons
    pylons.cache._push_object(config['pylons.app_globals'].cache)

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8',
        default_filters=['escape'],
        imports=['from webhelpers.html import escape'])

    # sets the c attribute access when don't existing attribute are accessed
    config['pylons.strict_tmpl_context'] = True
    test = os.path.split(config['__file__'])[-1] == 'test.ini'
    if test:
        if test_env is None:
            test_env = not int(os.environ.get('KALLITHEA_NO_TMP_PATH', 0))
        if test_index is None:
            test_index = not int(
                os.environ.get('KALLITHEA_WHOOSH_TEST_DISABLE', 0))
        if os.environ.get('TEST_DB'):
            # swap config if we pass enviroment variable
            config['sqlalchemy.db1.url'] = os.environ.get('TEST_DB')

        from kallithea.lib.utils import create_test_env, create_test_index
        from kallithea.tests import TESTS_TMP_PATH
        #set KALLITHEA_NO_TMP_PATH=1 to disable re-creating the database and
        #test repos
        if test_env:
            create_test_env(TESTS_TMP_PATH, config)
        #set KALLITHEA_WHOOSH_TEST_DISABLE=1 to disable whoosh index during tests
        if test_index:
            create_test_index(TESTS_TMP_PATH, config, True)

    DbManage.check_waitress()
    # MULTIPLE DB configs
    # Setup the SQLAlchemy database engine
    sa_engine_db1 = engine_from_config(config, 'sqlalchemy.db1.')
    init_model(sa_engine_db1)

    set_available_permissions(config)
    repos_path = make_ui('db').configitems('paths')[0][1]
    config['base_path'] = repos_path
    set_app_settings(config)

    instance_id = kallithea.CONFIG.get('instance_id')
    if instance_id == '*':
        instance_id = '%s-%s' % (platform.uname()[1], os.getpid())
        kallithea.CONFIG['instance_id'] = instance_id

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)

    # store config reference into our module to skip import magic of
    # pylons
    kallithea.CONFIG.update(config)
    set_vcs_config(kallithea.CONFIG)

    #check git version
    check_git_version()

    if str2bool(config.get('initial_repo_scan', True)):
        repo2db_mapper(ScmModel().repo_scan(repos_path),
                       remove_obsolete=False,
                       install_git_hook=False)
    return config
def load_environment(global_conf, app_conf, initial=False):
    """
    Configure the Pylons environment via the ``pylons.config``
    object
    """
    config = PylonsConfig()

    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(
        root=root,
        controllers=os.path.join(root, 'controllers'),
        static_files=os.path.join(root, 'public'),
        templates=[os.path.join(root, 'templates')]
    )

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='rhodecode', paths=paths)

    # store some globals into rhodecode
    rhodecode.CELERY_ON = str2bool(config['app_conf'].get('use_celery'))
    rhodecode.CELERY_EAGER = str2bool(config['app_conf'].get('celery.always.eager'))

    config['routes.map'] = make_map(config)
    config['pylons.app_globals'] = app_globals.Globals(config)
    config['pylons.h'] = helpers
    rhodecode.CONFIG = config

    load_rcextensions(root_path=config['here'])

    # Setup cache object as early as possible
    import pylons
    pylons.cache._push_object(config['pylons.app_globals'].cache)

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8', default_filters=['escape'],
        imports=['from webhelpers.html import escape'])

    # sets the c attribute access when don't existing attribute are accessed
    config['pylons.strict_tmpl_context'] = True
    test = os.path.split(config['__file__'])[-1] == 'test.ini'
    if test:
        if os.environ.get('TEST_DB'):
            # swap config if we pass enviroment variable
            config['sqlalchemy.db1.url'] = os.environ.get('TEST_DB')

        from rhodecode.lib.utils import create_test_env, create_test_index
        from rhodecode.tests import  TESTS_TMP_PATH
        # set RC_NO_TMP_PATH=1 to disable re-creating the database and
        # test repos
        if not int(os.environ.get('RC_NO_TMP_PATH', 0)):
            create_test_env(TESTS_TMP_PATH, config)
        # set RC_WHOOSH_TEST_DISABLE=1 to disable whoosh index during tests
        if not int(os.environ.get('RC_WHOOSH_TEST_DISABLE', 0)):
            create_test_index(TESTS_TMP_PATH, config, True)

    DbManage.check_waitress()
    # MULTIPLE DB configs
    # Setup the SQLAlchemy database engine
    sa_engine_db1 = engine_from_config(config, 'sqlalchemy.db1.')
    init_model(sa_engine_db1)

    set_available_permissions(config)
    repos_path = make_ui('db').configitems('paths')[0][1]
    config['base_path'] = repos_path
    set_rhodecode_config(config)

    instance_id = rhodecode.CONFIG.get('instance_id')
    if instance_id == '*':
        instance_id = '%s-%s' % (os.uname()[1], os.getpid())
        rhodecode.CONFIG['instance_id'] = instance_id

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)

    # store config reference into our module to skip import magic of
    # pylons
    rhodecode.CONFIG.update(config)
    set_vcs_config(rhodecode.CONFIG)

    #check git version
    check_git_version()

    if str2bool(config.get('initial_repo_scan', True)):
        repo2db_mapper(ScmModel().repo_scan(repos_path),
                       remove_obsolete=False, install_git_hook=False)
    return config
Exemple #9
0
def load_environment(global_conf, app_conf, with_db=True):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    # Pylons paths
    conf_copy = global_conf.copy()
    conf_copy.update(app_conf)
    site_templates = create_site_subdirectory('templates', app_conf=conf_copy)
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    client_containing = app_conf.get('adhocracy.client_location')
    if client_containing:
        client_root = os.path.join(client_containing, 'adhocracy_client')
        sys.path.insert(0, client_containing)
        import adhocracy_client.static
        sys.modules['adhocracy.static'] = adhocracy_client.static
    else:
        client_root = root
    import adhocracy.static
    paths = dict(
        root=root,
        controllers=os.path.join(root, 'controllers'),
        static_files=os.path.join(client_root, 'static'),
        templates=[site_templates,
                   os.path.join(client_root, 'templates')])

    # Initialize config with the basic options
    config = PylonsConfig()

    config.init_app(global_conf, app_conf, package='adhocracy', paths=paths)

    config['routes.map'] = make_map(config)
    config['pylons.app_globals'] = app_globals.Globals(config)
    config['pylons.h'] = adhocracy.lib.helpers

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8',
        default_filters=['escape'],
        imports=['from markupsafe import escape'])

    config['pylons.strict_tmpl_context'] = False

    # Setup the SQLAlchemy database engine
    engineOpts = {}
    if asbool(config.get('adhocracy.debug.sql', False)):
        engineOpts['connectionproxy'] = TimerProxy()

    engine = engine_from_config(config, 'sqlalchemy.', **engineOpts)
    init_model(engine)

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    init_site(config)
    if with_db:
        init_search()
    init_democracy()
    RQConfig.setup_from_config(config)

    return config
Exemple #10
0
def load_environment(global_conf, app_conf):
    """
    Configure the Pylons environment via the ``pylons.config``
    object
    """
    
    config = PylonsConfig()

    beaker.cache.clsmap['ext:redis'] = redis_.RedisManager

    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
            controllers=os.path.join(root, 'controllers'),
            static_files=os.path.join(root, 'public'),
            templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='civicboom', paths=paths)

    config['routes.map']         = make_map(config)
    config['pylons.app_globals'] = app_globals.Globals(config)

    #pylons.cache._push_object(config['pylons.app_globals'].cache)

    config['pylons.h'] = civicboom.lib.helpers

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
            directories=paths['templates'],
            error_handler=handle_mako_error,
            module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
            input_encoding='utf-8', default_filters=['escape'],
            imports=['from webhelpers.html import escape'])

    # Setup the SQLAlchemy database engine
    engine = engine_from_config(config, 'sqlalchemy.main.')
    init_model(engine)

    # Global translator setup
    #log.info("Init global i18n as en")
    #import gettext
    #langs = {
    #    "en": gettext.translation("civicboom", "./civicboom/i18n", languages=['en']),
    #}
    #langs["en"].install()

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    config_type_replacement(config) # Replace known string values in the config with actual type converted values

    # websetup.py tries to access pylons.config before it is
    # officially ready -- so make it unofficially ready and pray (HACK)
    for k, v in list(config.items()):
        pylons.config[k] = v

    # configure modules that used to require pylons.config
    wh.configure(pylons.config)

    # AllanC - unneeds as imports worker config directly
    #import civicboom.lib.communication.email_lib as email
    #email.configure(pylons.config)

    # AllanC changed it from worker.config=pylons.config because = replaces the reference. If worker.config is imported BEFORE this code is run then the importing class only access the empty original dict
    worker.config.update(pylons.config)
    # WARNING!!!
    # AllanC - NOTE!!! this update is fine AS LONG AS THE CONFIG IS NEVER CHANGED WHILE THE SITE IS RUNNING!
    #          in production this is never changed ... howver .. in testing we alter the state of the config to test ... even if most tests pass we could have some horrible hard to track down bugs because of this .update fix

    # set up worker processors
    if pylons.config['worker.queue.type'] in ["inline", "threads"]:
        from civicboom.worker import init_worker_functions
        init_worker_functions(worker)
    
    # set up worker queue
    if pylons.config['worker.queue.type'] == "inline":
        worker.init_queue(None)
    elif pylons.config['worker.queue.type'] == "threads":  # pragma: no cover
        worker.start_worker()
    elif pylons.config['worker.queue.type'] == "redis":  # pragma: no cover
        worker.init_queue(redis_.RedisQueue(redis_.redis_from_url(config['worker.queue.url']), platform.node()))
    else:  # pragma: no cover
        log.error("Invalid worker type: %s" % pylons.config['worker.queue.type'])

    # set up cache
    from civicboom.lib.cache import init_cache
    init_cache(config)

    # set up cbtv
    import cbutils.cbtv as t
    if config.get('telemetry'):  # pragma: no cover -- telemetry is disabled during coverage test
        t.set_log(config['telemetry'])

    init_model_extra() # This will trigger a set of additional initalizers

    return config
def load_environment(global_conf,
                     app_conf,
                     initial=False,
                     test_env=None,
                     test_index=None):
    """
    Configure the Pylons environment via the ``pylons.config``
    object
    """
    config = PylonsConfig()

    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = {
        'root': root,
        'controllers': os.path.join(root, 'controllers'),
        'static_files': os.path.join(root, 'public'),
        'templates': [os.path.join(root, 'templates')],
    }

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='rhodecode', paths=paths)

    # store some globals into rhodecode
    rhodecode.CELERY_ENABLED = str2bool(config['app_conf'].get('use_celery'))
    rhodecode.CELERY_EAGER = str2bool(
        config['app_conf'].get('celery.always.eager'))

    config['routes.map'] = make_map(config)

    if asbool(config.get('generate_js_files', 'false')):
        jsroutes = config['routes.map'].jsroutes()
        jsroutes_file_content = generate_jsroutes_content(jsroutes)
        jsroutes_file_path = os.path.join(paths['static_files'], 'js',
                                          'rhodecode', 'routes.js')

        with io.open(jsroutes_file_path, 'w', encoding='utf-8') as f:
            f.write(jsroutes_file_content)

    config['pylons.app_globals'] = app_globals.Globals(config)
    config['pylons.h'] = helpers
    rhodecode.CONFIG = config

    load_rcextensions(root_path=config['here'])

    # Setup cache object as early as possible
    import pylons
    pylons.cache._push_object(config['pylons.app_globals'].cache)

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8',
        default_filters=['escape'],
        imports=['from webhelpers.html import escape'])

    # sets the c attribute access when don't existing attribute are accessed
    config['pylons.strict_tmpl_context'] = True

    # Limit backends to "vcs.backends" from configuration
    backends = config['vcs.backends'] = aslist(config.get(
        'vcs.backends', 'hg,git'),
                                               sep=',')
    for alias in rhodecode.BACKENDS.keys():
        if alias not in backends:
            del rhodecode.BACKENDS[alias]
    log.info("Enabled backends: %s", backends)

    # initialize vcs client and optionally run the server if enabled
    vcs_server_uri = config.get('vcs.server', '')
    vcs_server_enabled = str2bool(config.get('vcs.server.enable', 'true'))
    start_server = (str2bool(config.get('vcs.start_server', 'false')) and
                    not int(os.environ.get('RC_VCSSERVER_TEST_DISABLE', '0')))
    if vcs_server_enabled and start_server:
        log.info("Starting vcsserver")
        start_vcs_server(server_and_port=vcs_server_uri,
                         protocol=utils.get_vcs_server_protocol(config),
                         log_level=config['vcs.server.log_level'])

    set_available_permissions(config)
    db_cfg = make_db_config(clear_session=True)

    repos_path = list(db_cfg.items('paths'))[0][1]
    config['base_path'] = repos_path

    config['vcs.hooks.direct_calls'] = _use_direct_hook_calls(config)
    config['vcs.hooks.protocol'] = _get_vcs_hooks_protocol(config)

    # store db config also in main global CONFIG
    set_rhodecode_config(config)

    # configure instance id
    utils.set_instance_id(config)

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)

    # store config reference into our module to skip import magic of pylons
    rhodecode.CONFIG.update(config)

    utils.configure_pyro4(config)
    utils.configure_vcs(config)
    if vcs_server_enabled:
        connect_vcs(vcs_server_uri, utils.get_vcs_server_protocol(config))

    import_on_startup = str2bool(config.get('startup.import_repos', False))
    if vcs_server_enabled and import_on_startup:
        repo2db_mapper(ScmModel().repo_scan(repos_path), remove_obsolete=False)
    return config
Exemple #12
0
def load_environment(global_conf, app_conf):
    """Configure the Pylons environment"""
    config = PylonsConfig()

    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files={},
                 content_files=[],
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='spline', paths=paths)

    extra_plugins = {}
    config_dir = os.path.dirname(global_conf['__file__'])
    paths['local'] = config_dir
    if config_dir != root:
        # This app isn't running out of a vanilla spline checkout.  See if it
        # publishes its own local plugin class, and if not, create a generic
        # one
        original_path = sys.path
        sys.path = [config_dir]
        try:
            local_module = __import__('plugin')
            plugin_class = local_module.LocalPlugin
        except:
            plugin_class = LocalPlugin
        finally:
            # Restore path no matter what!
            sys.path = original_path
        extra_plugins['local'] = plugin_class(config_dir)

    # Load plugins before routing so we have a list of controllers
    load_plugins(config, paths, extra_plugins)
    # Add our static directory
    paths['static_files']['spline'] = os.path.join(root, 'public')

    config['routes.map'] = make_map(config, content_dirs=paths['content_files'])
    config['pylons.app_globals'] = app_globals.Globals(config)
    pylons.cache._push_object(config['pylons.app_globals'].cache)
    config['pylons.h'] = spline.lib.helpers

    # Create the Mako TemplateLookup, with the default auto-escaping
    module_directory = {}
    if 'cache_dir' in app_conf:
        module_directory['module_directory'] \
            = os.path.join(app_conf['cache_dir'], 'templates')
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        input_encoding='utf-8', output_encoding='utf-8',
        imports=['from webhelpers.html import escape'],
        default_filters=['escape'],
        filesystem_checks=asbool(config.get('mako.filesystem_checks', True)),
        preprocessor=spline.lib.makoext.i18n_preprocessor,
        **module_directory)

    # Set up SQLAlchemy database engine
    engine = engine_from_config(config, 'sqlalchemy.')
    init_model(engine)

    # Set up our timer events
    # We attach them globally to the Engine class so we can automatically track
    # any other database connections used by the app. *coughpokedexcough*
    config['spline.sql_debugging'] = asbool(
        config.get('spline.sql_debugging', False))
    spline.lib.base.attach_timer(Engine)
    if config['spline.sql_debugging']:
        spline.lib.base.attach_query_log(Engine)

    # Backwards compatibility
    config['spline._sqlalchemy_proxy'] = None

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)

    # Use strict templating; none of this default-to-empty-string nonsense
    config['pylons.strict_c'] = True

    # Remove any stale cron lock
    del config['pylons.app_globals'].cache.get_cache('spline:cron')['LOCK']

    return config
Exemple #13
0
def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    config = PylonsConfig()

    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(
        root=root,
        controllers=os.path.join(root, "controllers"),
        static_files=os.path.join(root, "public"),
        templates=[os.path.join(root, "templates")],
    )

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package="mediacore", paths=paths)

    config["routes.map"] = make_map(config)
    config["pylons.app_globals"] = app_globals.Globals(config)
    config["pylons.h"] = mediacore.lib.helpers

    # Setup cache object as early as possible
    import pylons

    pylons.cache._push_object(config["pylons.app_globals"].cache)

    translator = Translator(ugettext)

    def enable_i18n_for_template(template):
        template.filters.insert(0, translator)

    # Create the Genshi TemplateLoader
    config["pylons.app_globals"].genshi_loader = TemplateLoader(
        search_path=paths["templates"], auto_reload=True, callback=enable_i18n_for_template
    )

    # Setup the SQLAlchemy database engine
    engine = engine_from_config(config, "sqlalchemy.")
    init_model(engine, config.get("db_table_prefix", None))

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    # TODO: Move as many of these custom options into an .ini file, or at least
    # to somewhere more friendly.

    # TODO: rework templates not to rely on this line:
    # See docstring in pylons.configuration.PylonsConfig for details.
    config["pylons.strict_tmpl_context"] = False

    # Genshi Default Search Path
    config["genshi_search_path"] = paths["templates"][0]

    config["thumb_sizes"] = {  # the dimensions (in pixels) to scale thumbnails
        Media._thumb_dir: {"s": (128, 72), "m": (160, 90), "l": (560, 315)},
        Podcast._thumb_dir: {"s": (128, 128), "m": (160, 160), "l": (600, 600)},
    }

    # The max number of results to return for any api listing
    config["api_media_max_results"] = 50

    # END CUSTOM CONFIGURATION OPTIONS

    return config
Exemple #14
0
def load_environment(global_conf, app_conf):
    """Configure the Pylons environment"""
    config = PylonsConfig()

    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files={},
                 content_files=[],
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='spline', paths=paths)

    extra_plugins = {}
    config_dir = os.path.dirname(global_conf['__file__'])
    paths['local'] = config_dir
    if config_dir != root:
        # This app isn't running out of a vanilla spline checkout.  See if it
        # publishes its own local plugin class, and if not, create a generic
        # one
        original_path = sys.path
        sys.path = [config_dir]
        try:
            local_module = __import__('plugin')
            plugin_class = local_module.LocalPlugin
        except:
            plugin_class = LocalPlugin
        finally:
            # Restore path no matter what!
            sys.path = original_path
        extra_plugins['local'] = plugin_class(config_dir)

    # Load plugins before routing so we have a list of controllers
    load_plugins(config, paths, extra_plugins)
    # Add our static directory
    paths['static_files']['spline'] = os.path.join(root, 'public')

    config['routes.map'] = make_map(config,
                                    content_dirs=paths['content_files'])
    config['pylons.app_globals'] = app_globals.Globals(config)
    pylons.cache._push_object(config['pylons.app_globals'].cache)
    config['pylons.h'] = spline.lib.helpers

    # Create the Mako TemplateLookup, with the default auto-escaping
    module_directory = {}
    if 'cache_dir' in app_conf:
        module_directory['module_directory'] \
            = os.path.join(app_conf['cache_dir'], 'templates')
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        input_encoding='utf-8',
        output_encoding='utf-8',
        imports=['from webhelpers.html import escape'],
        default_filters=['escape'],
        filesystem_checks=asbool(config.get('mako.filesystem_checks', True)),
        preprocessor=spline.lib.makoext.i18n_preprocessor,
        **module_directory)

    # Set up SQLAlchemy database engine
    engine = engine_from_config(config, 'sqlalchemy.')
    init_model(engine)

    # Set up our timer events
    # We attach them globally to the Engine class so we can automatically track
    # any other database connections used by the app. *coughpokedexcough*
    config['spline.sql_debugging'] = asbool(
        config.get('spline.sql_debugging', False))
    spline.lib.base.attach_timer(Engine)
    if config['spline.sql_debugging']:
        spline.lib.base.attach_query_log(Engine)

    # Backwards compatibility
    config['spline._sqlalchemy_proxy'] = None

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)

    # Use strict templating; none of this default-to-empty-string nonsense
    config['pylons.strict_c'] = True

    # Remove any stale cron lock
    del config['pylons.app_globals'].cache.get_cache('spline:cron')['LOCK']

    return config
def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config`` object"""
    config = PylonsConfig()

    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(root, 'public'),
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='mediadrop', paths=paths)
    env_dir = os.path.normpath(os.path.join(config['media_dir'], '..'))
    config.setdefault('env_dir', env_dir)

    # Initialize the plugin manager to load all active plugins
    plugin_mgr = PluginManager(config)

    mapper = create_mapper(config, plugin_mgr.controller_scan)
    events.Environment.before_route_setup(mapper)
    add_routes(mapper)
    events.Environment.after_route_setup(mapper)
    config['routes.map'] = mapper
    globals_ = Globals(config)
    globals_.plugin_mgr = plugin_mgr
    globals_.events = events
    config['pylons.app_globals'] = globals_
    config['pylons.h'] = mediadrop.lib.helpers

    # Setup cache object as early as possible
    pylons.cache._push_object(globals_.cache)

    i18n_env_dir = os.path.join(config['env_dir'], 'i18n')
    config['locale_dirs'] = plugin_mgr.locale_dirs()
    config['locale_dirs'].update({
        'mediadrop': (os.path.join(root, 'i18n'), i18n_env_dir),
        'FormEncode': (get_formencode_localedir(), i18n_env_dir),
    })

    def enable_i18n_for_template(template):
        translations = Translator(pylons.translator)
        translations.setup(template)

    # Create the Genshi TemplateLoader
    globals_.genshi_loader = TemplateLoader(
        search_path=paths['templates'] + plugin_mgr.template_loaders(),
        auto_reload=True,
        max_cache_size=100,
        callback=enable_i18n_for_template,
    )

    # Setup the SQLAlchemy database engine
    engine = engine_from_config(config, 'sqlalchemy.')
    init_model(engine, config.get('db_table_prefix', None))
    events.Environment.init_model()

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    #                                   any Pylons config options)

    # TODO: Move as many of these custom options into an .ini file, or at least
    #       to somewhere more friendly.

    # TODO: Rework templates not to rely on this line:
    #       See docstring in pylons.configuration.PylonsConfig for details.
    config['pylons.strict_tmpl_context'] = False

    config['thumb_sizes'] = { # the dimensions (in pixels) to scale thumbnails
        Media._thumb_dir: {
            's': (128,  72),
            'm': (160,  90),
            'l': (560, 315),
        },
        Podcast._thumb_dir: {
            's': (128, 128),
            'm': (160, 160),
            'l': (600, 600),
        },
    }

    # END CUSTOM CONFIGURATION OPTIONS

    events.Environment.loaded(config)

    return config
Exemple #16
0
def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config`` object"""
    config = PylonsConfig()

    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(root, 'public'),
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='mediadrop', paths=paths)
    env_dir = os.path.normpath(os.path.join(config['media_dir'], '..'))
    config.setdefault('env_dir', env_dir)

    # Initialize the plugin manager to load all active plugins
    plugin_mgr = PluginManager(config)

    mapper = create_mapper(config, plugin_mgr.controller_scan)
    events.Environment.before_route_setup(mapper)
    add_routes(mapper)
    events.Environment.after_route_setup(mapper)
    config['routes.map'] = mapper
    config['pylons.app_globals'] = app_globals.Globals(config)
    config['pylons.app_globals'].plugin_mgr = plugin_mgr
    config['pylons.app_globals'].events = events
    config['pylons.h'] = mediadrop.lib.helpers

    # Setup cache object as early as possible
    pylons.cache._push_object(config['pylons.app_globals'].cache)

    i18n_env_dir = os.path.join(config['env_dir'], 'i18n')
    config['locale_dirs'] = plugin_mgr.locale_dirs()
    config['locale_dirs'].update({
        'mediadrop': (os.path.join(root, 'i18n'), i18n_env_dir),
        'FormEncode': (get_formencode_localedir(), i18n_env_dir),
    })

    def enable_i18n_for_template(template):
        translations = Translator(translator)
        translations.setup(template)

    # Create the Genshi TemplateLoader
    config['pylons.app_globals'].genshi_loader = TemplateLoader(
        search_path=paths['templates'] + plugin_mgr.template_loaders(),
        auto_reload=True,
        max_cache_size=100,
        callback=enable_i18n_for_template,
    )

    # Setup the SQLAlchemy database engine
    engine = engine_from_config(config, 'sqlalchemy.')
    init_model(engine, config.get('db_table_prefix', None))
    events.Environment.init_model()

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    #                                   any Pylons config options)

    # TODO: Move as many of these custom options into an .ini file, or at least
    #       to somewhere more friendly.

    # TODO: Rework templates not to rely on this line:
    #       See docstring in pylons.configuration.PylonsConfig for details.
    config['pylons.strict_tmpl_context'] = False

    config['thumb_sizes'] = { # the dimensions (in pixels) to scale thumbnails
        Media._thumb_dir: {
            's': (128,  72),
            'm': (160,  90),
            'l': (560, 315),
        },
        Podcast._thumb_dir: {
            's': (128, 128),
            'm': (160, 160),
            'l': (600, 600),
        },
    }

    # END CUSTOM CONFIGURATION OPTIONS

    events.Environment.loaded(config)

    return config
Exemple #17
0
def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(root, 'public'),
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    if is_pylons_0:
        config = pylons_config
    else:
        config = PylonsConfig()
    config.init_app(global_conf, app_conf, package='fts3rest', paths=paths)

    config['routes.map'] = make_map(config)
    config['pylons.app_globals'] = app_globals.Globals(config)
    config['pylons.h'] = fts3rest.lib.helpers

    # Setup cache object as early as possible
    import pylons
    pylons.cache._push_object(config['pylons.app_globals'].cache)

    # If fts3.config is set, load configuration from there
    fts3_config_file = config.get('fts3.config')
    if fts3_config_file:
        fts3cfg = fts3_config_load(fts3_config_file)
        # Let the database be overriden by fts3rest.ini
        if 'sqlalchemy.url' in config and 'sqlalchemy.url' in fts3cfg:
            del fts3cfg['sqlalchemy.url']
        config.update(fts3cfg)

    # Setup the SQLAlchemy database engine
    kwargs = dict()
    if config['sqlalchemy.url'].startswith('mysql://'):
        import MySQLdb.cursors
        kwargs['connect_args'] = {'cursorclass': MySQLdb.cursors.SSCursor}
    engine = engine_from_config(config,
                                'sqlalchemy.',
                                pool_recycle=7200,
                                **kwargs)
    init_model(engine)

    # Disable for sqlite the isolation level to work around issues with savepoints
    if config['sqlalchemy.url'].startswith('sqlite'):

        @event.listens_for(engine, "connect")
        def do_connect(dbapi_connection, connection_record):
            dbapi_connection.isolation_level = None

    # Catch dead connections
    event.listens_for(engine, 'checkout')(connection_validator)
    event.listens_for(engine, 'connect')(connection_set_sqlmode)

    # Mako templating
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'], )

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    return config