當前位置: 首頁>>代碼示例>>Python>>正文


Python dotenv.find_dotenv方法代碼示例

本文整理匯總了Python中dotenv.find_dotenv方法的典型用法代碼示例。如果您正苦於以下問題:Python dotenv.find_dotenv方法的具體用法?Python dotenv.find_dotenv怎麽用?Python dotenv.find_dotenv使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在dotenv的用法示例。


在下文中一共展示了dotenv.find_dotenv方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: refresh_access_token

# 需要導入模塊: import dotenv [as 別名]
# 或者: from dotenv import find_dotenv [as 別名]
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") 
開發者ID:lttkgp,項目名稱:C-3PO,代碼行數:26,代碼來源:facebook.py

示例2: store_key

# 需要導入模塊: import dotenv [as 別名]
# 或者: from dotenv import find_dotenv [as 別名]
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"]) 
開發者ID:microsoft,項目名稱:DistributedDeepLearning,代碼行數:22,代碼來源:storage.py

示例3: setup_logging_env

# 需要導入模塊: import dotenv [as 別名]
# 或者: from dotenv import find_dotenv [as 別名]
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 
開發者ID:manifoldai,項目名稱:orbyter-cookiecutter,代碼行數:26,代碼來源:{{ cookiecutter.repo_name.replace(

示例4: load_config

# 需要導入模塊: import dotenv [as 別名]
# 或者: from dotenv import find_dotenv [as 別名]
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) 
開發者ID:microsoft,項目名稱:seismic-deeplearning,代碼行數:10,代碼來源:config.py

示例5: __init__

# 需要導入模塊: import dotenv [as 別名]
# 或者: from dotenv import find_dotenv [as 別名]
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) 
開發者ID:microsoft,項目名稱:seismic-deeplearning,代碼行數:11,代碼來源:config.py

示例6: main

# 需要導入模塊: import dotenv [as 別名]
# 或者: from dotenv import find_dotenv [as 別名]
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,
    ) 
開發者ID:microsoft,項目名稱:AI,代碼行數:35,代碼來源:aml_creation.py

示例7: load_config

# 需要導入模塊: import dotenv [as 別名]
# 或者: from dotenv import find_dotenv [as 別名]
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) 
開發者ID:microsoft,項目名稱:DistributedDeepLearning,代碼行數:13,代碼來源:config.py

示例8: select_subscription

# 需要導入模塊: import dotenv [as 別名]
# 或者: from dotenv import find_dotenv [as 別名]
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) 
開發者ID:microsoft,項目名稱:DistributedDeepLearning,代碼行數:17,代碼來源:tasks.py

示例9: populate_args_from_dotenv

# 需要導入模塊: import dotenv [as 別名]
# 或者: from dotenv import find_dotenv [as 別名]
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 
開發者ID:msalvaris,項目名稱:gpu_monitor,代碼行數:14,代碼來源:dotenv.py

示例10: pytest_load_initial_conftests

# 需要導入模塊: import dotenv [as 別名]
# 或者: from dotenv import find_dotenv [as 別名]
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) 
開發者ID:quiqua,項目名稱:pytest-dotenv,代碼行數:6,代碼來源:plugin.py

示例11: load_dotenv

# 需要導入模塊: import dotenv [as 別名]
# 或者: from dotenv import find_dotenv [as 別名]
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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:49,代碼來源:cli.py

示例12: main

# 需要導入模塊: import dotenv [as 別名]
# 或者: from dotenv import find_dotenv [as 別名]
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) 
開發者ID:microsoft,項目名稱:AI,代碼行數:52,代碼來源:aml_attach_blob.py


注:本文中的dotenv.find_dotenv方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。