Python dotenv.load_dotenv() Examples

The following are 27 code examples of dotenv.load_dotenv(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dotenv , or try the search function .
Example #1
Source File: cli.py    From Building-Recommendation-Systems-with-Python with MIT License 7 votes vote down vote up
def main(self, *args, **kwargs):
        # Set a global flag that indicates that we were invoked from the
        # command line interface. This is detected by Flask.run to make the
        # call into a no-op. This is necessary to avoid ugly errors when the
        # script that is loaded here also attempts to start a server.
        os.environ['FLASK_RUN_FROM_CLI'] = 'true'

        if get_load_dotenv(self.load_dotenv):
            load_dotenv()

        obj = kwargs.get('obj')

        if obj is None:
            obj = ScriptInfo(create_app=self.create_app,
                             set_debug_flag=self.set_debug_flag)

        kwargs['obj'] = obj
        kwargs.setdefault('auto_envvar_prefix', 'FLASK')
        return super(FlaskGroup, self).main(*args, **kwargs) 
Example #2
Source File: cli.py    From recruit with Apache License 2.0 6 votes vote down vote up
def main(self, *args, **kwargs):
        # Set a global flag that indicates that we were invoked from the
        # command line interface. This is detected by Flask.run to make the
        # call into a no-op. This is necessary to avoid ugly errors when the
        # script that is loaded here also attempts to start a server.
        os.environ['FLASK_RUN_FROM_CLI'] = 'true'

        if get_load_dotenv(self.load_dotenv):
            load_dotenv()

        obj = kwargs.get('obj')

        if obj is None:
            obj = ScriptInfo(create_app=self.create_app)

        kwargs['obj'] = obj
        kwargs.setdefault('auto_envvar_prefix', 'FLASK')
        return super(FlaskGroup, self).main(*args, **kwargs) 
Example #3
Source File: cli.py    From scylla with Apache License 2.0 6 votes vote down vote up
def main(self, *args, **kwargs):
        # Set a global flag that indicates that we were invoked from the
        # command line interface. This is detected by Flask.run to make the
        # call into a no-op. This is necessary to avoid ugly errors when the
        # script that is loaded here also attempts to start a server.
        os.environ['FLASK_RUN_FROM_CLI'] = 'true'

        if get_load_dotenv(self.load_dotenv):
            load_dotenv()

        obj = kwargs.get('obj')

        if obj is None:
            obj = ScriptInfo(create_app=self.create_app,
                             set_debug_flag=self.set_debug_flag)

        kwargs['obj'] = obj
        kwargs.setdefault('auto_envvar_prefix', 'FLASK')
        return super(FlaskGroup, self).main(*args, **kwargs) 
Example #4
Source File: cli.py    From scylla with Apache License 2.0 6 votes vote down vote up
def __init__(self, add_default_commands=True, create_app=None,
                 add_version_option=True, load_dotenv=True,
                 set_debug_flag=True, **extra):
        params = list(extra.pop('params', None) or ())

        if add_version_option:
            params.append(version_option)

        AppGroup.__init__(self, params=params, **extra)
        self.create_app = create_app
        self.load_dotenv = load_dotenv
        self.set_debug_flag = set_debug_flag

        if add_default_commands:
            self.add_command(run_command)
            self.add_command(shell_command)
            self.add_command(routes_command)

        self._loaded_plugin_commands = False 
Example #5
Source File: config.py    From boss with MIT License 6 votes vote down vote up
def resolve_dotenv_file(path, stage=None):
    '''
    Resolve dotenv file and load environment vars if it exists.
    If stage parameter is provided, then stage specific .env file is resolved,
    for instance .env.production if stage=production etc.
    If stage is None, just .env file is resolved.
    '''
    filename = '.env' + ('' if not stage else '.{}'.format(stage))
    dotenv_path = os.path.join(path, filename)
    fallback_path = os.path.join(path, '.env')

    if fs.exists(dotenv_path):
        info('Resolving env file: {}'.format(cyan(dotenv_path)))
        dotenv.load_dotenv(dotenv_path)

    elif fs.exists(fallback_path):
        info('Resolving env file: {}'.format(cyan(fallback_path)))
        dotenv.load_dotenv(fallback_path) 
Example #6
Source File: cli.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def main(self, *args, **kwargs):
        # Set a global flag that indicates that we were invoked from the
        # command line interface. This is detected by Flask.run to make the
        # call into a no-op. This is necessary to avoid ugly errors when the
        # script that is loaded here also attempts to start a server.
        os.environ['FLASK_RUN_FROM_CLI'] = 'true'

        if get_load_dotenv(self.load_dotenv):
            load_dotenv()

        obj = kwargs.get('obj')

        if obj is None:
            obj = ScriptInfo(create_app=self.create_app,
                             set_debug_flag=self.set_debug_flag)

        kwargs['obj'] = obj
        kwargs.setdefault('auto_envvar_prefix', 'FLASK')
        return super(FlaskGroup, self).main(*args, **kwargs) 
Example #7
Source File: cli.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def __init__(self, add_default_commands=True, create_app=None,
                 add_version_option=True, load_dotenv=True,
                 set_debug_flag=True, **extra):
        params = list(extra.pop('params', None) or ())

        if add_version_option:
            params.append(version_option)

        AppGroup.__init__(self, params=params, **extra)
        self.create_app = create_app
        self.load_dotenv = load_dotenv
        self.set_debug_flag = set_debug_flag

        if add_default_commands:
            self.add_command(run_command)
            self.add_command(shell_command)
            self.add_command(routes_command)

        self._loaded_plugin_commands = False 
Example #8
Source File: cli.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def __init__(self, add_default_commands=True, create_app=None,
                 add_version_option=True, load_dotenv=True,
                 set_debug_flag=True, **extra):
        params = list(extra.pop('params', None) or ())

        if add_version_option:
            params.append(version_option)

        AppGroup.__init__(self, params=params, **extra)
        self.create_app = create_app
        self.load_dotenv = load_dotenv
        self.set_debug_flag = set_debug_flag

        if add_default_commands:
            self.add_command(run_command)
            self.add_command(shell_command)
            self.add_command(routes_command)

        self._loaded_plugin_commands = False 
Example #9
Source File: cli.py    From android_universal with MIT License 6 votes vote down vote up
def __init__(self, add_default_commands=True, create_app=None,
                 add_version_option=True, load_dotenv=True, **extra):
        params = list(extra.pop('params', None) or ())

        if add_version_option:
            params.append(version_option)

        AppGroup.__init__(self, params=params, **extra)
        self.create_app = create_app
        self.load_dotenv = load_dotenv

        if add_default_commands:
            self.add_command(run_command)
            self.add_command(shell_command)
            self.add_command(routes_command)

        self._loaded_plugin_commands = False 
Example #10
Source File: cli.py    From android_universal with MIT License 6 votes vote down vote up
def main(self, *args, **kwargs):
        # Set a global flag that indicates that we were invoked from the
        # command line interface. This is detected by Flask.run to make the
        # call into a no-op. This is necessary to avoid ugly errors when the
        # script that is loaded here also attempts to start a server.
        os.environ['FLASK_RUN_FROM_CLI'] = 'true'

        if get_load_dotenv(self.load_dotenv):
            load_dotenv()

        obj = kwargs.get('obj')

        if obj is None:
            obj = ScriptInfo(create_app=self.create_app)

        kwargs['obj'] = obj
        kwargs.setdefault('auto_envvar_prefix', 'FLASK')
        return super(FlaskGroup, self).main(*args, **kwargs) 
Example #11
Source File: train.py    From MLOps with MIT License 5 votes vote down vote up
def main():

    model_name, dataset_name = getRuntimeArgs()
    dotenv.load_dotenv()

    run = Run.get_context()

    if run._run_id.startswith("_OfflineRun"):
        run = None

    credit_data_df = None

    #Load data from Dataset or from local file(for offline runs)
    if run is None:
        dataset_filename = os.environ.get("DATASET_FILE_NAME", )
        credit_data_df = pd.read_csv("dataset/" +dataset_filename)
    else:
        dataset = Dataset.get_by_name(workspace=run.experiment.workspace, name=dataset_name)
        #dataset = run.input_datasets[dataset_name]
        credit_data_df = dataset.to_pandas_dataframe()

    clf = model_train(credit_data_df, run)

    #copying to "outputs" directory, automatically uploads it to azure ml
    output_dir = './outputs/'
    os.makedirs(output_dir, exist_ok=True)
    joblib.dump(value=clf, filename=output_dir+model_name)

    #run.upload_file(name="./outputs/" + model_file_name, path_or_stream=model_file_name) 
Example #12
Source File: batch_score.py    From MLOps with MIT License 5 votes vote down vote up
def init():
    global model
    print("GPU USAGE: ", tf.test.is_gpu_available())
    model_path = Model.get_model_path(MODEL_FILE_NAME)
    dotenv.load_dotenv()
    print("model_path: ", model_path)
    # deserialize the model file back into a sklearn model
    model = keras.models.load_model(model_path)
    print("Model Loaded") 
Example #13
Source File: mlp_lite.py    From texta with GNU General Public License v3.0 5 votes vote down vote up
def _reload_env(self):
        import dotenv
        dotenv.load_dotenv(".env") 
Example #14
Source File: mlp.py    From texta with GNU General Public License v3.0 5 votes vote down vote up
def _reload_env(self):
        import dotenv
        dotenv.load_dotenv(".env") 
Example #15
Source File: AzureMLUtils.py    From MLOps with MIT License 5 votes vote down vote up
def get_workspace():
    dotenv.load_dotenv()
    workspace_name = os.environ.get("WORKSPACE")
    resource_group = os.environ.get("RESOURCE_GROUP")
    subscription_id = os.environ.get("SUBSCRIPTION_ID")
    tenant_id = os.environ.get("TENANT_ID")
    app_id = os.environ.get("SP_APP_ID")
    app_secret = os.environ.get("SP_APP_SECRET")

    service_principal = ServicePrincipalAuthentication(
        tenant_id=tenant_id,
        service_principal_id=app_id,
        service_principal_password=app_secret)

    try:
        aml_workspace = Workspace.get(
            name=workspace_name,
            subscription_id=subscription_id,
            resource_group=resource_group,
            auth=service_principal)

        return aml_workspace
    except Exception as caught_exception:
        print("Error while retrieving Workspace...")
        print(str(caught_exception))
        sys.exit(1) 
Example #16
Source File: manage.py    From Wagtail-Pipit with MIT License 5 votes vote down vote up
def if_exists_load_env(name):
    inspect_file = inspect.getfile(inspect.currentframe())
    env_path = os.path.dirname(os.path.abspath(inspect_file))
    env_file = "{env_path}/{name}".format(env_path=env_path, name=name)

    if os.path.exists(env_file):
        dotenv.load_dotenv(env_file) 
Example #17
Source File: __init__.py    From myaas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def load_dotenv():
    current_path = os.path.abspath(os.path.dirname(__file__))
    dotenv_file = os.path.join(current_path, ".env")
    if os.path.isfile(dotenv_file):
        dotenv.load_dotenv(dotenv_file) 
Example #18
Source File: cli.py    From recruit with Apache License 2.0 5 votes vote down vote up
def __init__(self, add_default_commands=True, create_app=None,
                 add_version_option=True, load_dotenv=True, **extra):
        params = list(extra.pop('params', None) or ())

        if add_version_option:
            params.append(version_option)

        AppGroup.__init__(self, params=params, **extra)
        self.create_app = create_app
        self.load_dotenv = load_dotenv

        if add_default_commands:
            self.add_command(run_command)
            self.add_command(shell_command)
            self.add_command(routes_command)

        self._loaded_plugin_commands = False 
Example #19
Source File: manage.py    From Wagtail-Pipit with MIT License 5 votes vote down vote up
def if_exists_load_env(name):
    inspect_file = inspect.getfile(inspect.currentframe())
    env_path = os.path.dirname(os.path.abspath(inspect_file))
    env_file = "{env_path}/{name}".format(env_path=env_path, name=name)

    if os.path.exists(env_file):
        dotenv.load_dotenv(env_file) 
Example #20
Source File: __init__.py    From clean-architecture with MIT License 5 votes vote down vote up
def bootstrap_app() -> App:
    """This is bootstrap function independent from the context.

    This should be used for Web, CLI, or worker context."""
    config_path = os.environ.get(
        "CONFIG_PATH", os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, ".env_file")
    )
    dotenv.load_dotenv(config_path)
    settings = {
        "payments.login": os.environ["PAYMENTS_LOGIN"],
        "payments.password": os.environ["PAYMENTS_PASSWORD"],
        "email.host": os.environ["EMAIL_HOST"],
        "email.port": os.environ["EMAIL_PORT"],
        "email.username": os.environ["EMAIL_USERNAME"],
        "email.password": os.environ["EMAIL_PASSWORD"],
        "email.from.name": os.environ["EMAIL_FROM_NAME"],
        "email.from.address": os.environ["EMAIL_FROM_ADDRESS"],
        "redis.host": os.environ["REDIS_HOST"],
    }

    engine = create_engine(os.environ["DB_DSN"])
    connection_provider = ThreadlocalConnectionProvider(engine)
    dependency_injector = _setup_dependency_injection(settings, connection_provider)
    _setup_orm_events(dependency_injector)

    _create_db_schema(engine)  # TEMPORARY

    return App(connection_provider, dependency_injector) 
Example #21
Source File: ecs.py    From devopsloft with GNU General Public License v3.0 5 votes vote down vote up
def PrepareEnvironmentVars(environment, action):
    devwebsport = 'DEV_WEB_GUEST_SECURE_PORT'
    dotenv.load_dotenv()
    envArray = os.environ.copy()
    envArray['RUN_BY_PYTHON'] = 'yes'
    envArray['ENVIRONMENT'] = environment
    envArray['HOMEPATH'] = '/home'
    if (environment == 'dev'):
        envArray['WEB_HOST_PORT'] = envArray['DEV_WEB_HOST_PORT']
        envArray['WEB_GUEST_PORT'] = envArray['DEV_WEB_GUEST_PORT']
        envArray['WEB_HOST_SECURE_PORT'] = \
            envArray['DEV_WEB_HOST_SECURE_PORT']
        envArray['WEB_GUEST_SECURE_PORT'] = envArray[devwebsport]
    if (environment == 'stage'):
        envArray['WEB_HOST_PORT'] = envArray['STAGE_WEB_HOST_PORT']
        envArray['WEB_GUEST_PORT'] = envArray['STAGE_WEB_GUEST_PORT']
        envArray['WEB_HOST_SECURE_PORT'] = \
            envArray['STAGE_WEB_HOST_SECURE_PORT']
        envArray['WEB_GUEST_SECURE_PORT'] = envArray[devwebsport]
        envArray['AWS_S3_BUCKET'] = envArray['STAGE_AWS_S3_BUCKET']
    if (environment == 'prod'):
        envArray['WEB_HOST_PORT'] = envArray['PROD_WEB_HOST_PORT']
        envArray['WEB_GUEST_PORT'] = envArray['PRDO_WEB_GUEST_PORT']
        envArray['WEB_HOST_SECURE_PORT'] = \
            envArray['PROD_WEB_HOST_SECURE_PORT']
        envArray['WEB_GUEST_SECURE_PORT'] = envArray[devwebsport]
        envArray['AWS_S3_BUCKET'] = envArray['PROD_AWS_S3_BUCKET']
    return envArray 
Example #22
Source File: spin-docker.py    From devopsloft with GNU General Public License v3.0 5 votes vote down vote up
def PrepareEnvironmentVars(environmentName, action):
    # Reads the .env file from the repository
    # Returns an array with all the env vars, inclduing modificatoins per env
    devwebsport = 'DEV_WEB_GUEST_SECURE_PORT'
    dotenv.load_dotenv()
    envArray = os.environ.copy()
    envArray['RUN_BY_PYTHON'] = 'yes'
    envArray['ENVIRONMENT'] = environmentName
    envArray['HOMEPATH'] = '/home'
    if (environmentName == 'dev'):
        envArray['WEB_HOST_PORT'] = envArray['DEV_WEB_HOST_PORT']
        envArray['WEB_GUEST_PORT'] = envArray['DEV_WEB_GUEST_PORT']
        envArray['WEB_HOST_SECURE_PORT'] = \
            envArray['DEV_WEB_HOST_SECURE_PORT']
        envArray['WEB_GUEST_SECURE_PORT'] = envArray[devwebsport]
    if (environmentName == 'stage'):
        envArray['WEB_HOST_PORT'] = envArray['STAGE_WEB_HOST_PORT']
        envArray['WEB_GUEST_PORT'] = envArray['STAGE_WEB_GUEST_PORT']
        envArray['WEB_HOST_SECURE_PORT'] = \
            envArray['STAGE_WEB_HOST_SECURE_PORT']
        envArray['WEB_GUEST_SECURE_PORT'] = envArray[devwebsport]
        envArray['AWS_S3_BUCKET'] = envArray['STAGE_AWS_S3_BUCKET']
    if (environmentName == 'prod'):
        envArray['WEB_HOST_PORT'] = envArray['PROD_WEB_HOST_PORT']
        envArray['WEB_GUEST_PORT'] = envArray['PRDO_WEB_GUEST_PORT']
        envArray['WEB_HOST_SECURE_PORT'] = \
            envArray['PROD_WEB_HOST_SECURE_PORT']
        envArray['WEB_GUEST_SECURE_PORT'] = envArray[devwebsport]
        envArray['AWS_S3_BUCKET'] = envArray['PROD_AWS_S3_BUCKET']
    return envArray 
Example #23
Source File: core.py    From pipenv with MIT License 5 votes vote down vote up
def load_dot_env():
    """Loads .env file into sys.environ."""
    if not environments.PIPENV_DONT_LOAD_ENV:
        # If the project doesn't exist yet, check current directory for a .env file
        project_directory = project.project_directory or "."
        dotenv_file = environments.PIPENV_DOTENV_LOCATION or os.sep.join(
            [project_directory, ".env"]
        )

        if os.path.isfile(dotenv_file):
            click.echo(
                crayons.normal(fix_utf8("Loading .env environment variables…"), bold=True),
                err=True,
            )
        else:
            if environments.PIPENV_DOTENV_LOCATION:
                click.echo(
                    "{0}: file {1}={2} does not exist!!\n{3}".format(
                        crayons.red("Warning", bold=True),
                        crayons.normal("PIPENV_DOTENV_LOCATION", bold=True),
                        crayons.normal(environments.PIPENV_DOTENV_LOCATION, bold=True),
                        crayons.red("Not loading environment variables.", bold=True),
                    ),
                    err=True,
                )
        dotenv.load_dotenv(dotenv_file, override=True)
        six.moves.reload_module(environments) 
Example #24
Source File: cli.py    From scylla with Apache License 2.0 4 votes vote down vote up
def load_dotenv(path=None):
    """Load "dotenv" files in order of precedence to set environment variables.

    If an env var is already set it is not overwritten, so earlier files in the
    list are preferred over later files.

    Changes the current working directory to the location of the first file
    found, with the assumption that it is in the top level project directory
    and will be where the Python path should import local packages from.

    This is a no-op if `python-dotenv`_ is not installed.

    .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme

    :param path: Load the file at this location instead of searching.
    :return: ``True`` if a file was loaded.

    .. versionadded:: 1.0
    """
    if dotenv is None:
        if path or os.path.exists('.env') or os.path.exists('.flaskenv'):
            click.secho(
                ' * Tip: There are .env files present.'
                ' Do "pip install python-dotenv" to use them.',
                fg='yellow')
        return

    if path is not None:
        return dotenv.load_dotenv(path)

    new_dir = None

    for name in ('.env', '.flaskenv'):
        path = dotenv.find_dotenv(name, usecwd=True)

        if not path:
            continue

        if new_dir is None:
            new_dir = os.path.dirname(path)

        dotenv.load_dotenv(path)

    if new_dir and os.getcwd() != new_dir:
        os.chdir(new_dir)

    return new_dir is not None  # at least one file was located and loaded 
Example #25
Source File: cli.py    From Building-Recommendation-Systems-with-Python with MIT License 4 votes vote down vote up
def load_dotenv(path=None):
    """Load "dotenv" files in order of precedence to set environment variables.

    If an env var is already set it is not overwritten, so earlier files in the
    list are preferred over later files.

    Changes the current working directory to the location of the first file
    found, with the assumption that it is in the top level project directory
    and will be where the Python path should import local packages from.

    This is a no-op if `python-dotenv`_ is not installed.

    .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme

    :param path: Load the file at this location instead of searching.
    :return: ``True`` if a file was loaded.

    .. versionadded:: 1.0
    """
    if dotenv is None:
        if path or os.path.exists('.env') or os.path.exists('.flaskenv'):
            click.secho(
                ' * Tip: There are .env files present.'
                ' Do "pip install python-dotenv" to use them.',
                fg='yellow')
        return

    if path is not None:
        return dotenv.load_dotenv(path)

    new_dir = None

    for name in ('.env', '.flaskenv'):
        path = dotenv.find_dotenv(name, usecwd=True)

        if not path:
            continue

        if new_dir is None:
            new_dir = os.path.dirname(path)

        dotenv.load_dotenv(path)

    if new_dir and os.getcwd() != new_dir:
        os.chdir(new_dir)

    return new_dir is not None  # at least one file was located and loaded 
Example #26
Source File: cli.py    From recruit with Apache License 2.0 4 votes vote down vote up
def load_dotenv(path=None):
    """Load "dotenv" files in order of precedence to set environment variables.

    If an env var is already set it is not overwritten, so earlier files in the
    list are preferred over later files.

    Changes the current working directory to the location of the first file
    found, with the assumption that it is in the top level project directory
    and will be where the Python path should import local packages from.

    This is a no-op if `python-dotenv`_ is not installed.

    .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme

    :param path: Load the file at this location instead of searching.
    :return: ``True`` if a file was loaded.

    .. versionadded:: 1.0
    """
    if dotenv is None:
        if path or os.path.exists('.env') or os.path.exists('.flaskenv'):
            click.secho(
                ' * Tip: There are .env files present.'
                ' Do "pip install python-dotenv" to use them.',
                fg='yellow')
        return

    if path is not None:
        return dotenv.load_dotenv(path)

    new_dir = None

    for name in ('.env', '.flaskenv'):
        path = dotenv.find_dotenv(name, usecwd=True)

        if not path:
            continue

        if new_dir is None:
            new_dir = os.path.dirname(path)

        dotenv.load_dotenv(path)

    if new_dir and os.getcwd() != new_dir:
        os.chdir(new_dir)

    return new_dir is not None  # at least one file was located and loaded 
Example #27
Source File: cli.py    From android_universal with MIT License 4 votes vote down vote up
def load_dotenv(path=None):
    """Load "dotenv" files in order of precedence to set environment variables.

    If an env var is already set it is not overwritten, so earlier files in the
    list are preferred over later files.

    Changes the current working directory to the location of the first file
    found, with the assumption that it is in the top level project directory
    and will be where the Python path should import local packages from.

    This is a no-op if `python-dotenv`_ is not installed.

    .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme

    :param path: Load the file at this location instead of searching.
    :return: ``True`` if a file was loaded.

    .. versionadded:: 1.0
    """
    if dotenv is None:
        if path or os.path.exists('.env') or os.path.exists('.flaskenv'):
            click.secho(
                ' * Tip: There are .env files present.'
                ' Do "pip install python-dotenv" to use them.',
                fg='yellow')
        return

    if path is not None:
        return dotenv.load_dotenv(path)

    new_dir = None

    for name in ('.env', '.flaskenv'):
        path = dotenv.find_dotenv(name, usecwd=True)

        if not path:
            continue

        if new_dir is None:
            new_dir = os.path.dirname(path)

        dotenv.load_dotenv(path)

    if new_dir and os.getcwd() != new_dir:
        os.chdir(new_dir)

    return new_dir is not None  # at least one file was located and loaded