Create configuration from Django settings or environment.
187732
def from_settings(cls):
        """"""
        from cloud_browser.app_settings import settings
        from django.core.exceptions import ImproperlyConfigured

        conn_cls = conn_fn = None
        datastore = settings.CLOUD_BROWSER_DATASTORE
        if datastore == 'AWS':
            # Try AWS
            from cloud_browser.cloud.aws import AwsConnection
            account = settings.CLOUD_BROWSER_AWS_ACCOUNT
            secret_key = settings.CLOUD_BROWSER_AWS_SECRET_KEY
            if account and secret_key:
                conn_cls = AwsConnection
                conn_fn = lambda: AwsConnection(account, secret_key)

        if datastore == 'Google':
            # Try Google Storage
            from cloud_browser.cloud.google import GsConnection
            account = settings.CLOUD_BROWSER_GS_ACCOUNT
            secret_key = settings.CLOUD_BROWSER_GS_SECRET_KEY
            if account and secret_key:
                conn_cls = GsConnection
                conn_fn = lambda: GsConnection(account, secret_key)

        elif datastore == 'Rackspace':
            # Try Rackspace
            account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
            secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
            servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
            authurl = settings.CLOUD_BROWSER_RACKSPACE_AUTHURL
            if account and secret_key:
                from cloud_browser.cloud.rackspace import RackspaceConnection
                conn_cls = RackspaceConnection
                conn_fn = lambda: RackspaceConnection(
                    account,
                    secret_key,
                    servicenet=servicenet,
                    authurl=authurl)

        elif datastore == 'Filesystem':
            # Mock filesystem
            root = settings.CLOUD_BROWSER_FILESYSTEM_ROOT
            if root is not None:
                from cloud_browser.cloud.fs import FilesystemConnection
                conn_cls = FilesystemConnection
                conn_fn = lambda: FilesystemConnection(root)

        if conn_cls is None:
            raise ImproperlyConfigured(
                "No suitable credentials found for datastore: %s." %
                datastore)

        # Adjust connection function.
        conn_fn = staticmethod(conn_fn)

        # Directly cache attributes.
        cls.__connection_cls = conn_cls
        cls.__connection_fn = conn_fn

        return conn_cls, conn_fn
357245
def create_config():
    """"""
    file_exists = exists(CONFIG_FILE)
    if not file_exists:
        # Set directories
        config.add_section('Directories')
        defaults = [
            ('AbstractRetrieval', expanduser('~/.scopus/abstract_retrieval')),
            ('AffiliationSearch', expanduser('~/.scopus/affiliation_search')),
            ('AuthorRetrieval', expanduser('~/.scopus/author_retrieval')),
            ('AuthorSearch', expanduser('~/.scopus/author_search')),
            ('CitationOverview', expanduser('~/.scopus/citation_overview')),
            ('ContentAffiliationRetrieval', expanduser('~/.scopus/affiliation_retrieval')),
            ('ScopusSearch', expanduser('~/.scopus/scopus_search'))
        ]
        for key, value in defaults:
            config.set('Directories', key, value)
            if not exists(value):
                makedirs(value)
        # Set authentication
        config.add_section('Authentication')
        prompt_key = "Please enter your API Key, obtained from "\
                     "http://dev.elsevier.com/myapikey.html: \n"
        if py3:
            key = input(prompt_key)
        else:
            key = raw_input(prompt_key)
        config.set('Authentication', 'APIKey', key)
        prompt_token = "API Keys are sufficient for most users.  If you "\
                       "have to use Authtoken authentication, please enter "\
                       "the token, otherwise press Enter: \n"
        if py3:
            token = input(prompt_token)
        else:
            token = raw_input(prompt_token)
        if len(token) > 0:
            config.set('Authentication', 'InstToken', token)
        # Write out
        with open(CONFIG_FILE, 'w') as f:
            config.write(f)
    else:
        text = "Configuration file already exists at {}; process to create "\
               "the file aborted.  Please open the file and edit the "\
               "entries manually.".format(CONFIG_FILE)
        raise FileExistsError(text)
703552
def settings(instance):
    """"""
    with open(instance.root_dir + '/Config/config.yml') as config:
        config = yaml.load(config)
        instance.name = config['name']
        instance.port = config['web']['port']
        # default host
        instance.host = "http://localhost"
        if 'host' in config['web']:
            instance.host = config['web']['host']
        instance.debug = config['debug']
    return instance
833095
def create_settings(pkg, repo_dest, db_user, db_name, db_password, db_host,
                    db_port):
    
    vars = {'pkg': pkg,
            'db_user': db_user,
            'db_name': db_name,
            'db_password': db_password or '',
            'db_host': db_host or '',
            'db_port': db_port or '',
            'hmac_date': datetime.now().strftime('%Y-%m-%d'),
            'hmac_key': generate_key(32),
            'secret_key': generate_key(32)}
    with dir_path(repo_dest):
        shutil.copyfile('%s/settings/local.py-dist' % pkg,
                        '%s/settings/local.py' % pkg)
        patch("""\
            --- a/%(pkg)s/settings/local.py
            +++ b/%(pkg)s/settings/local.py
            @@ -9,11 +9,11 @@ from . import base
             DATABASES = {
                 'default': {
                     'ENGINE': 'django.db.backends.mysql',
            -        'NAME': 'playdoh_app',
            -        'USER': 'root',
            -        'PASSWORD': '',
            -        'HOST': '',
            -        'PORT': '',
            +        'NAME': '%(db_name)s',
            +        'USER': '%(db_user)s',
            +        'PASSWORD': '%(db_password)s',
            +        'HOST': '%(db_host)s',
            +        'PORT': '%(db_port)s',
                     'OPTIONS': {
                         'init_command': 'SET storage_engine=InnoDB',
                         'charset' : 'utf8',
            @@ -51,14 +51,14 @@ DEV = True
             # Playdoh ships with Bcrypt+HMAC by default because it's the most secure.
             # To use bcrypt, fill in a secret HMAC key. It cannot be blank.
             HMAC_KEYS = {
            -    #'2012-06-06': 'some secret',
            +    '%(hmac_date)s': '%(hmac_key)s',
             }

             from django_sha2 import get_password_hashers
             PASSWORD_HASHERS = get_password_hashers(base.BASE_PASSWORD_HASHERS, HMAC_KEYS)

             # Make this unique, and don't share it with anybody.  It cannot be blank.
            -SECRET_KEY = ''
            +SECRET_KEY = '%(secret_key)s'

             # Uncomment these to activate and customize Celery:
             # CELERY_ALWAYS_EAGER = False  # required to activate celeryd
            """ % vars)
356991
def init(self, args=None):
        """"""
        from .logs import exception

        self._setup_user_dir()
        self._init_settings_file()

        try:
            self.update(self._settings_from_file())
        except Exception:
            exception("Can't load settings from file", sys.exc_info())

        try:
            self.update(self._settings_from_env())
        except Exception:
            exception("Can't load settings from env", sys.exc_info())

        self.update(self._settings_from_args(args))
1099866
def create(file_path):
    """"""
    if os.path.exists(file_path):
        raise IOError("There is already a configuration file at %s" %
                      file_path)
    with open(file_path, 'w') as f:
        config = configparser.ConfigParser()
        config.add_section('misc')
        config.set('misc', 'config-version', '1.0')
        default_nb_name = os.path.split(os.path.dirname(file_path))[1]
        config.set('misc', 'nb-name', default_nb_name)
        config.add_section('root')
        config.set('root', 'path', '.')
        config.add_section('models')
        config.set('models', 'module', 'models')
        config.add_section('tests')
        config.set('tests', 'module', 'tests')
        config.add_section('suites')
        config.set('suites', 'module', 'suites')
        config.write(f)
462266
def _manage_cmd(cmd, settings=None):
    # type: () -> None
    
    import sys
    from os import environ
    from peltak.core import conf
    from peltak.core import context
    from peltak.core import log

    sys.path.insert(0, conf.get('src_dir'))

    settings = settings or conf.get('django.settings', None)
    environ.setdefault("DJANGO_SETTINGS_MODULE", settings)

    args = sys.argv[0:-1] + cmd

    if context.get('pretend', False):
        log.info("Would run the following manage command:\n<90>{}", args)
    else:
        from django.core.management import execute_from_command_line
        execute_from_command_line(args)
186674
def configure_settings():
    
    if not settings.configured:
        # Determine the database settings depending on if a test_db var is set in CI mode or not
        test_db = os.environ.get('DB', None)
        if test_db is None:
            db_config = {
                'ENGINE': 'django.db.backends.postgresql_psycopg2',
                'NAME': 'ambition',
                'USER': 'ambition',
                'PASSWORD': 'ambition',
                'HOST': 'db'
            }
        elif test_db == 'postgres':
            db_config = {
                'ENGINE': 'django.db.backends.postgresql_psycopg2',
                'USER': 'postgres',
                'NAME': 'manager_utils',
                }
        elif test_db == 'sqlite':
            db_config = {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': 'manager_utils',
                }
        else:
            raise RuntimeError('Unsupported test DB {0}'.format(test_db))

        settings.configure(
            TEST_RUNNER='django_nose.NoseTestSuiteRunner',
            NOSE_ARGS=['--nocapture', '--nologcapture', '--verbosity=1'],
            MIDDLEWARE_CLASSES={},
            DATABASES={
                'default': db_config,
            },
            INSTALLED_APPS=(
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.sessions',
                'django.contrib.admin',
                'manager_utils',
                'manager_utils.tests',
            ),
            ROOT_URLCONF='manager_utils.urls',
            DEBUG=False,
        )
1169711
def make_config(self, data: dict):
        """"""
        self.validate_config(data)
        config_data = self.prepare_config(data)
        return config_data
983715
def Initialize(config=None,
               external_hostname = None,
               admin_password = None,
               redownload_templates = False,
               repack_templates = True,
               token = None):
  """"""

  print("Checking write access on config %s" % config["Config.writeback"])
  if not os.access(config.parser.filename, os.W_OK):
    raise IOError("Config not writeable (need sudo?)")

  print("\nStep 0: Importing Configuration from previous installation.")
  options_imported = 0
  prev_config_file = config.Get("ConfigUpdater.old_config", default=None)
  if prev_config_file and os.access(prev_config_file, os.R_OK):
    print("Found config file %s." % prev_config_file)
    # pytype: disable=wrong-arg-count
    if builtins.input("Do you want to import this configuration? "
                      "[yN]: ").upper() == "Y":
      options_imported = ImportConfig(prev_config_file, config)
    # pytype: enable=wrong-arg-count
  else:
    print("No old config file found.")

  print("\nStep 1: Setting Basic Configuration Parameters")
  print("We are now going to configure the server using a bunch of questions.")
  ConfigureDatastore(config)
  ConfigureUrls(config, external_hostname=external_hostname)
  ConfigureEmails(config)

  print("\nStep 2: Key Generation")
  if config.Get("PrivateKeys.server_key", default=None):
    if options_imported > 0:
      print("Since you have imported keys from another installation in the "
            "last step,\nyou probably do not want to generate new keys now.")
    # pytype: disable=wrong-arg-count
    if (builtins.input("You already have keys in your config, do you want to"
                       " overwrite them? [yN]: ").upper() or "N") == "Y":
      config_updater_keys_util.GenerateKeys(config, overwrite_keys=True)
    # pytype: enable=wrong-arg-count
  else:
    config_updater_keys_util.GenerateKeys(config)

  FinalizeConfigInit(
      config,
      token,
      admin_password=admin_password,
      redownload_templates=redownload_templates,
      repack_templates=repack_templates,
      prompt=True)
66226
def configuration(*args, **kwargs):
    """"""
    try:
        config_kwargs = {'mapping_class': kwargs.pop('mapping_class')}
    except KeyError:
        config_kwargs = {}
    cm = ConfigurationManager(*args, **kwargs)
    return cm.get_config(**config_kwargs)
153148
def create(config_file, profile):
    """"""

    # determine the config file path
    if config_file:
        click.echo("Using configuration file: {}".format(config_file))
    else:
        # path not given, try to detect; or use default, but allow user to override
        config_file = get_configfile_path()
        if config_file:
            click.echo("Found existing configuration file: {}".format(config_file))
        else:
            config_file = get_default_configfile_path()
            click.echo("Configuration file not found; the default location is: {}".format(config_file))
        config_file = default_text_input("Configuration file path", config_file)
        config_file = os.path.expanduser(config_file)

    # create config_file path
    config_base = os.path.dirname(config_file)
    if config_base and not os.path.exists(config_base):
        if click.confirm("Configuration file path does not exist. Create it?", abort=True):
            try:
                os.makedirs(config_base)
            except Exception as e:
                click.echo("Error creating configuration path: {}".format(e))
                return 1

    # try loading existing config, or use defaults
    try:
        config = load_config_from_files([config_file])
    except:
        config = get_default_config()

    # determine profile
    if profile:
        click.echo("Using profile: {}".format(profile))
    else:
        existing = config.sections()
        if existing:
            profiles = 'create new or choose from: {}'.format(', '.join(existing))
            default_profile = ''
        else:
            profiles = 'create new'
            default_profile = 'prod'
        profile = default_text_input("Profile (%s)" % profiles, default_profile, optional=False)

    if not config.has_section(profile):
        config.add_section(profile)

    # fill out the profile variables
    variables = 'endpoint token client solver proxy'.split()
    prompts = ['API endpoint URL',
               'Authentication token',
               'Default client class (qpu or sw)',
               'Default solver']
    for var, prompt in zip(variables, prompts):
        default_val = config.get(profile, var, fallback=None)
        val = default_text_input(prompt, default_val)
        if val:
            val = os.path.expandvars(val)
        if val != default_val:
            config.set(profile, var, val)

    try:
        with open(config_file, 'w') as fp:
            config.write(fp)
    except Exception as e:
        click.echo("Error writing to configuration file: {}".format(e))
        return 2

    click.echo("Configuration saved.")
    return 0
478606
def create_config(config_fname, override_url=None):
    '''
    
    '''
    config_path = os.path.dirname(config_fname)
    os.makedirs(config_path, exist_ok=True)

    # Consider override URL. Only used by test suite runs
    settings = DEFAULT_SETTINGS_FLAT
    if override_url:
        settings['url'] = override_url

    # Create fresh config file, including new UUID
    with open(config_fname, 'wt') as config:
        config.write(DEFAULT_FILE_CONTENT.format(**settings))
    return True
801955
def _construct_config(self, basedir, port, name=None, isreplset=False):
        """"""
        if isreplset:
            return self._construct_replset(basedir=basedir, portstart=port,
                                           name=name,
                                           num_nodes=list(range(
                                               self.args['config'])),
                                           arbiter=False, extra='--configsvr')
        else:
            datapath = self._create_paths(basedir, name)
            self._construct_mongod(os.path.join(datapath, 'db'),
                                   os.path.join(datapath, 'mongod.log'),
                                   port, replset=None, extra='--configsvr')
772612
def _settings_from_file(self):
        """"""
        settings = load_source(
            'settings', text_type(self.user_dir.joinpath('settings.py')))
        return {key: getattr(settings, key)
                for key in const.DEFAULT_SETTINGS.keys()
                if hasattr(settings, key)}
617631
def _setup(self, name=None):
        
        envvar = self.__dict__['env_var']
        if envvar:
            settings_file = os.environ.get(envvar)
        else:
            settings_file = self.__dict__['file_path']

        if not settings_file:
            msg = ("Requested settings, but none can be obtained for the envvar."
                   "Since no config filepath can be obtained, a default config "
                   "will be used.")
            logger.error(msg)
            raise OSError(msg)

        self._wrapped = Settings(settings_file)
404620
def create_from_config(self, config):
        

        configService = ConfigService()
        template = TemplateService()

        template.output = config["output"]["location"]

        template_file = configService.get_template_from_config(config)
        template.input = os.path.basename(template_file)
        template.env = Environment(loader=FileSystemLoader(os.path.dirname(template_file)))

        return template