Python dotenv.find_dotenv() Examples

The following are 16 code examples of dotenv.find_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: facebook.py    From C-3PO with MIT License 6 votes vote down vote up
def refresh_access_token():
    """
    Refresh short access token
    """
    dotenvfile = find_dotenv()
    load_dotenv(dotenvfile)
    with warnings.catch_warnings(record=True) as warns:
        warnings.simplefilter("ignore", ResourceWarning)
        dotenv.get_key(dotenvfile, "FB_LONG_ACCESS_TOKEN")
        warns = filter(lambda i: issubclass(i.category, UserWarning), warns)
        if warns:
            request_url = FB_URL + "oauth/access_token"
            request_payload = {
                "grant_type": "fb_exchange_token",
                "client_id": FB_APP_ID,
                "client_secret": FB_APP_SECRET,
                "fb_exchange_token": FB_SHORT_ACCESS_TOKEN,
            }
            response = REQ_SESSION.get(request_url, params=request_payload).json()
            dotenvfile = find_dotenv()
            load_dotenv(dotenvfile)
            print(response)
            dotenv.set_key(dotenvfile, "FB_LONG_ACCESS_TOKEN", response["access_token"])
            PAYLOAD["access_token"] = dotenv.get_key(dotenvfile, "FB_LONG_ACCESS_TOKEN") 
Example #2
Source File: storage.py    From DistributedDeepLearning with MIT License 6 votes vote down vote up
def store_key(c):
    """Retrieves premium storage account key from Azure and stores it in .env file
    """
    logger = logging.getLogger(__name__)
    account_name = env_values.get("ACCOUNT_NAME")
    resource_group = env_values.get("RESOURCE_GROUP")

    if (
        "ACCOUNT_KEY" in env_values
        and env_values["ACCOUNT_KEY"]
        and len(env_values["ACCOUNT_KEY"]) > 0
    ):
        logger.info(f"Account key already in env file")
        return None

    cmd = f"az storage account keys list -n {account_name} -g {resource_group}"
    result = c.run(cmd)
    keys = json.loads(result.stdout)
    env_file = find_dotenv(raise_error_if_not_found=True)
    set_key(env_file, "ACCOUNT_KEY", keys[0]["value"]) 
Example #3
Source File: logging.py    From orbyter-cookiecutter with MIT License 6 votes vote down vote up
def setup_logging_env(main: Callable) -> Callable:
    """Decorator to set up loggging and load env variables

    Args:
        main: top level function (typically main triggered by CLI)

    Return:
        function after setting up logging and loading env variables
    """

    def wrapper(*args, **kwargs):
        setup_logging()
        load_dotenv(find_dotenv())
        logger.info(f"Loaded environment variables")
        logger.info(f"Starting {main.__name__}() in {sys.argv[0]}")
        t = TicToc()
        t.tic()
        main(*args, **kwargs)
        logger.info(
            f"Finished {main.__name__}() in "
            f"{timedelta(seconds=np.ceil(t.tocvalue()))}"
        )

    return wrapper 
Example #4
Source File: config.py    From seismic-deeplearning with MIT License 5 votes vote down vote up
def load_config(dot_env_path: find_dotenv(raise_error_if_not_found=True)):
    """ Load the variables from the .env file
    Returns:
        .env variables(dict)
    """
    logger = logging.getLogger(__name__)
    logger.info(f"Found config in {dot_env_path}")
    return dotenv_values(dot_env_path) 
Example #5
Source File: config.py    From seismic-deeplearning with MIT License 5 votes vote down vote up
def __init__(self):
        self._dot_env_path = find_dotenv(raise_error_if_not_found=True)

        for k, v in load_config(dot_env_path=self._dot_env_path).items():
            self.__dict__[k] = _convert(v)

        for k, v in _DEFAULTS.items():
            if k not in self.__dict__:
                setattr(self, k, v) 
Example #6
Source File: aml_creation.py    From AI with MIT License 5 votes vote down vote up
def main(argv):  
  try:
     opts, args = getopt.getopt(argv,"hs:rg:wn:wr:",["subscription_id=","resource_group=","workspace_name=", "workspace_region="])
  except getopt.GetoptError:
     print 'aml_creation.py -s <subscription_id> -rg <resource_group> -wn <workspace_name> -wr <workspace_region>'
     sys.exit(2)
  for opt, arg in opts:
     if opt == '-h':
        print 'aml_creation.py -s <subscription_id> -rg <resource_group> -wn <workspace_name> -wr <workspace_region>'
        sys.exit()
     elif opt in ("-s", "--subscription_id"):
        subscription_id = arg
     elif opt in ("-rg", "--resource_group"):
        resource_group = arg
     elif opt in ("-wn", "--workspace_name"):
        workspace_name = arg
     elif opt in ("-wr", "--workspace_region"):
        workspace_region = arg
        
    env_path = find_dotenv()
    if env_path == "":
        Path(".env").touch()
        env_path = find_dotenv()

    ws = Workspace.create(
      name=workspace_name,
      subscription_id=subscription_id,
      resource_group=resource_group,
      location=workspace_region,
      create_resource_group=True,
      auth=get_auth(env_path),
      exist_ok=True,
    ) 
Example #7
Source File: config.py    From DistributedDeepLearning with MIT License 5 votes vote down vote up
def load_config():
    """ Load the variables from the .env file

    Returns:
        .env variables(dict)

    """
    logger = logging.getLogger(__name__)
    dot_env_path = find_dotenv(raise_error_if_not_found=True)
    logger.info(f"Found config in {dot_env_path}")
    return dotenv_values(dot_env_path) 
Example #8
Source File: tasks.py    From DistributedDeepLearning with MIT License 5 votes vote down vote up
def select_subscription(c, sub_id=env_values.get("SUBSCRIPTION_ID", None)):
    """Select Azure subscription to use
    
    Note:
        If sub_id isn't provided or found in env values interactive prompt is created asking for sub id selection
        The selection is then recorded in the env file

    Args:
        sub_id (string, optional): [description]. Defaults to env_values.get("SUBSCRIPTION_ID", None).
    """
    env_file = find_dotenv(raise_error_if_not_found=True)
    if sub_id is None or sub_id == "":
        sub_id = _prompt_sub_id_selection(c)
        set_key(env_file, "SUBSCRIPTION_ID", sub_id)
    c.run(f"az account set -s {sub_id}", pty=True) 
Example #9
Source File: dotenv.py    From gpu_monitor with MIT License 5 votes vote down vote up
def populate_args_from_dotenv(func):
    logger = _logger()
    try:
        dotenv_path = find_dotenv(raise_error_if_not_found=True)
        logger.info('Found .evn, loading variables')
        env_dict = dotenv_values(dotenv_path=dotenv_path)
        par_func = partial(func, **env_dict)
        par_func.__doc__ = func.__doc__
        return par_func
    except IOError:
        logger.info('Didn\'t find .env')
        return func 
Example #10
Source File: plugin.py    From pytest-dotenv with MIT License 5 votes vote down vote up
def pytest_load_initial_conftests(args, early_config, parser):
    _override = early_config.getini("env_override_existing_values")
    for filename in early_config.getini("env_files"):
        load_dotenv(find_dotenv(filename, usecwd=True), override=_override) 
Example #11
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 #12
Source File: aml_attach_blob.py    From AI with MIT License 4 votes vote down vote up
def main(argv):  
  try:
     opts, args = getopt.getopt(argv,"hs:rg:wn:wr:dsn:cn:an:ak:drg:",
      ["subscription_id=","resource_group=","workspace_name=", "workspace_region=","blob_datastore_name=","container_name=","account_name=","account_key=","datastore_rg="])
  except getopt.GetoptError:
     print 'aml_creation.py -s <subscription_id> -rg <resource_group> -wn <workspace_name> -wr <workspace_region>'
     sys.exit(2)
  for opt, arg in opts:
     if opt == '-h':
        print 'aml_creation.py -s <subscription_id> -rg <resource_group> -wn <workspace_name> -wr <workspace_region>'
        sys.exit()
     elif opt in ("-s", "--subscription_id"):
        subscription_id = arg
     elif opt in ("-rg", "--resource_group"):
        resource_group = arg
     elif opt in ("-wn", "--workspace_name"):
        workspace_name = arg
     elif opt in ("-wr", "--workspace_region"):
        workspace_region = arg
     elif opt in ("-dsn", "--blob_datastore_name"):
        workspace_region = arg
     elif opt in ("-cn", "--container_name"):
        workspace_region = arg
     elif opt in ("-an", "--account_name"):
        workspace_region = arg
     elif opt in ("-ak", "--account_key"):
        workspace_region = arg
     elif opt in ("-drg", "--datastore_rg"):
        workspace_region = arg
        
    env_path = find_dotenv()
    if env_path == "":
        Path(".env").touch()
        env_path = find_dotenv()

    ws = Workspace.create(
      name=workspace_name,
      subscription_id=subscription_id,
      resource_group=resource_group,
      location=workspace_region,
      create_resource_group=True,
      auth=get_auth(env_path),
      exist_ok=True,
    )
    blob_datastore = Datastore.register_azure_blob_container(workspace=ws, 
                                                         datastore_name=blob_datastore_name, 
                                                         container_name=container_name, 
                                                         account_name=account_name,
                                                         account_key=account_key,
                                                         resource_group=datastore_rg) 
Example #13
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 #14
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 #15
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 #16
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