Flask app factory function.

    Args:
        config (Optional[path]): path to a Python module config file
        config_obj (Optional[class]): Python config object
763122
def create_app(config=None, config_obj=None):
    
    app = Flask(__name__)
    # configure application from external configs
    configure_app(app, config=config, config_obj=config_obj)
    # register different parts of the application
    register_blueprints(app)
    # setup extensions
    bind_extensions(app)
    return app
1063814
def build_config(config, filename=None):
    
    # Done here since it seems not to be possible to detect if an argument
    # was supplied by the user or if it's the default argument.
    # If using type=lambda v: None if v in ('transparent', 'trans') else v
    # we cannot detect if "None" comes from "transparent" or the default value
    for clr in ('color', 'background'):
        val = config.pop(clr, None)
        if val in ('transparent', 'trans'):
            config[clr] = None
        elif val:
            config[clr] = val
    # SVG
    for name in ('svgid', 'svgclass', 'lineclass'):
        if config.get(name, None) is None:
            config.pop(name, None)
    if config.pop('no_classes', False):
        config['svgclass'] = None
        config['lineclass'] = None
    if filename is not None:
        ext = filename[filename.rfind('.') + 1:].lower()
        if ext == 'svgz':  # There is no svgz serializer, use same config as svg
            ext = 'svg'
        supported_args = _EXT_TO_KW_MAPPING.get(ext, ())
        # Drop unsupported arguments from config rather than getting a
        # "unsupported keyword" exception
        for k in list(config):
            if k not in supported_args:
                del config[k]
    return config
541588
def init_app(module, BASE_DIR, **kwargs):
    
    global app

    def init_config():
        """
        Load settings module and attach values to the application
        config dictionary
        """
        if 'FLASK_PHILO_SETTINGS_MODULE' not in os.environ:
            raise ConfigurationError('No settings has been defined')

        app.config['BASE_DIR'] = BASE_DIR

        # default settings
        for v in dir(default_settings):
            if not v.startswith('_'):
                app.config[v] = getattr(default_settings, v)

        app.debug = app.config['DEBUG']

        # app settings
        settings = importlib.import_module(
            os.environ['FLASK_PHILO_SETTINGS_MODULE'])
        for v in dir(settings):
            if not v.startswith('_'):
                app.config[v] = getattr(settings, v)

        def init_urls():
            # Reads urls definition from URLs file and bind routes and views
            urls_module = importlib.import_module(app.config['URLS'])
            for route in urls_module.URLS:
                app.add_url_rule(
                    route[0], view_func=route[1].as_view(route[2]))

        def init_logging():
            """
            initialize logger for the app
            """

            hndlr = logging.StreamHandler()
            formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            hndlr.setFormatter(formatter)
            app.logger.addHandler(hndlr)
            log_level = app.config['LOG_LEVEL']
            app.logger.setLevel(getattr(logging, log_level))

        def init_flask_oauthlib():
            """
            http://flask-oauthlib.readthedocs.io/en/latest/oauth2.html
            """
            oauth.init_app(app)

        def init_cors(app):
            """
            Initializes cors protection if config
            """

            if 'CORS' in app.config:
                CORS(
                    app,
                    resources=app.config['CORS'],
                    supports_credentials=app.config.get(
                        "CORS_SUPPORT_CREDENTIALS",
                        False
                    ),
                    allow_headers=app.config.get(
                        "CORS_ALLOW_HEADERS",
                        "Content-Type,Authorization,accept-language,accept"
                    )
                )

        init_db(g, app)
        init_logging()
        init_urls()
        init_flask_oauthlib()
        init_jinja2(g, app)
        init_cors(app)
    app = Flask(module)
    init_config()
    return app
1248865
def read_file(self, file_path):
        '''  '''
        getLogger().info("Loading app config from {} file: {}".format(self.__mode, file_path))
        if self.__mode == AppConfig.JSON:
            return json.loads(FileHelper.read(file_path), object_pairs_hook=OrderedDict)
        elif self.__mode == AppConfig.INI:
            config = configparser.ConfigParser(allow_no_value=True)
            config.read(file_path)
            return config
1234052
def import_config(config_path):
    
    if not os.path.isfile(config_path):
        raise ConfigBuilderError(
                'Could not find config file: ' + config_path)
    loader = importlib.machinery.SourceFileLoader(config_path, config_path)
    module = loader.load_module()

    if not hasattr(module, 'config') or not isinstance(module.config, Config):
        raise ConfigBuilderError(
            'Could not load config file "{}": config files must contain '
            'a variable called "config" that is '
            'assigned to a Config object.'.format(config_path))
    return module.config
735270
def _getConfigFile(self, config):
        

        joinPath = lambda p: (os.path.join(p) if isinstance(p, (tuple, list)) else p)

        if self.filepathConfig is not None and self.filenameConfig is not None:
            if hasattr(config, self.filepathConfig) and hasattr(config, self.filenameConfig):
                path = joinPath(getattr(config, self.filepathConfig))
                name = getattr(config, self.filenameConfig)

                if os.path.isfile(os.path.join(path, name)):
                    return open(os.path.join(path, name), 'r')

        if self.filepath is not None and self.filename is not None:
            path = joinPath(self.filepath)
            name = self.filename

            if os.path.isfile(os.path.join(path, name)):
                return open(os.path.join(path, name), 'r')
1365181
def get_app(config):
    
    mongo_client = MongoClient(host=config.get('mongo_opt', {}).get('host', 'localhost'))
    database = mongo_client[config.get('mongo_opt', {}).get('database', 'INGInious')]

    # Create the FS provider
    if "tasks_directory" not in config:
        raise RuntimeError("WebDav access is only supported if INGInious is using a local filesystem to access tasks")

    fs_provider = LocalFSProvider(config["tasks_directory"])
    course_factory, task_factory = create_factories(fs_provider, {}, None, WebAppCourse, WebAppTask)
    user_manager = UserManager(MongoStore(database, 'sessions'), database, config.get('superadmins', []))

    config = dict(wsgidav_app.DEFAULT_CONFIG)
    config["provider_mapping"] = {"/": INGIniousFilesystemProvider(course_factory, task_factory)}
    config["domaincontroller"] = INGIniousDAVDomainController(user_manager, course_factory)
    config["verbose"] = 0

    app = wsgidav_app.WsgiDAVApp(config)

    return app
1131720
function(configPath, configNames, config) {
	var configsUsed = [];

	config = config || projectConfig;

	// work with the raw configuration object
	if (config && config.root) {
		config = config.root();
	}

	config = convict(config);
	configPath = path.resolve(appPath, configPath);
	configNames = configNames || [];

	configNames.forEach(function(configName) {
		var file;

		// Ignore local config in production mode
		if (configName == 'local' && nodeEnv === 'production') { return; }

		file = path.join(configPath, 'config-'+configName);
		file += configName === 'default' ? '.js' : '.json';

		if (fs.existsSync(file)) {

			if (configName === 'default') {
				config = convict( require(file) );
				config.load(dynamicDefaults);
			}
			else {
				config.loadFile( file );
			}

			// logging
			configName === 'default' ? configsUsed.push('xtc defaults') : configsUsed.push(configName);
		}
	});

	// be informative
	!process.env.testRun
		&& configsUsed.push('env', 'args')
		&& console.log('configuration:', configsUsed.join(' < '));

	return config;
}
780679
def from_config(cls, cfg, **kwargs):
        """"""
        cfg = dict(cfg, **kwargs)
        pythonpath = cfg.get('pythonpath', [])
        if 'here' in cfg:
            pythonpath.append(cfg['here'])
        for path in pythonpath:
            sys.path.append(os.path.expanduser(path))
        prog = cls.server and 'irc3d' or 'irc3'
        if cfg.get('debug'):
            cls.venusian_categories.append(prog + '.debug')
        if cfg.get('interactive'):  # pragma: no cover
            import irc3.testing
            context = getattr(irc3.testing, cls.__name__)(**cfg)
        else:
            context = cls(**cfg)
        if cfg.get('raw'):
            context.include('irc3.plugins.log',
                            venusian_categories=[prog + '.debug'])
        return context
757928
def _load_config_file(self):
        
        LOGGER.info('Loading configuration from %s', self._file_path)
        if self._file_path.endswith('json'):
            config = self._load_json_config()
        else:
            config = self._load_yaml_config()
        for key, value in [(k, v) for k, v in config.items()]:
            if key.title() != key:
                config[key.title()] = value
                del config[key]
        return flatdict.FlatDict(config)
187733
def _load_config(initial_namespace=None, defaults=None):
    # type: (Optional[str], Optional[str]) -> ConfigLoader
    
    # load defaults
    if defaults:
        config = ConfigLoader()
        config.update_from_object(defaults)

    namespace = getattr(config, 'CONFIG_NAMESPACE', initial_namespace)
    app_config = getattr(config, 'APP_CONFIG', None)

    # load customised config
    if app_config:
        if namespace is None:
            config.update_from_object(app_config)
        else:
            _temp = ConfigLoader()
            _temp.update_from_object(app_config, lambda key: key.startswith(namespace))
            config.update(_temp.namespace(namespace))

    return config
542845
def load_config(self, configfile=None, override_config=None):
        
        self.config = configobj.ConfigObj()

        # Load in the collector's defaults
        if self.get_default_config() is not None:
            self.config.merge(self.get_default_config())

        if configfile is not None:
            self.configfile = os.path.abspath(configfile)

        if self.configfile is not None:
            config = load_config(self.configfile)

            if 'collectors' in config:
                if 'default' in config['collectors']:
                    self.config.merge(config['collectors']['default'])

                if self.name in config['collectors']:
                    self.config.merge(config['collectors'][self.name])

        if override_config is not None:
            if 'collectors' in override_config:
                if 'default' in override_config['collectors']:
                    self.config.merge(override_config['collectors']['default'])

                if self.name in override_config['collectors']:
                    self.config.merge(override_config['collectors'][self.name])

        self.process_config()
379511
def main(global_config, **settings):
    
    config = Configurator(settings=settings)
    config.set_session_factory(session_factory)
    config.include('pyramid_jinja2')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('index', '/')
    config.add_route('attrs', '/attrs/')
    config.add_route('metadata', '/metadata/')
    config.scan()
    return config.make_wsgi_app()
192450
function buildConfig (_config) {
  _config.datastore = Object.assign({}, defaultDatastore, _get(_config, 'datastore', {}))

  return _config
}
834478
def config_(cls, key, default=None):
        
        return cls._app.config.get(key, default)
278092
def generate_payload(self, config, context):
        
        from flask import current_app, session, request as _request

        current_view = current_app.view_functions[_request.endpoint]
        if hasattr(current_view, 'view_class'):
            component = '.'.join((current_view.__module__, current_view.view_class.__name__))
        else:
            component = current_view.__module__
        cgi_data = {
            k: v
            for k, v in iteritems(_request.headers)
        }
        cgi_data.update({
            'REQUEST_METHOD': _request.method
        })
        payload = {
            'url': _request.base_url,
            'component': component,
            'action': _request.endpoint,
            'params': {},
            'session': filter_dict(dict(session), config.params_filters),
            'cgi_data': cgi_data,
            'context': context
        }

        # Add query params
        params = filter_dict(dict(_request.args), config.params_filters)
        params.update(filter_dict(dict(_request.form), config.params_filters))

        payload['params'] = params

        return payload
907441
def read_config(config_path=CONFIG_PATH):
    
    if not os.path.isfile(config_path):
        raise IOError("No config file found at %s" % config_path)
    config_parser = configparser.ConfigParser()
    config_parser.read(config_path)
    config = _config_parser_to_defaultdict(config_parser)
    return config