我可以调用 load_dotenv 两次吗?

Can I call load_dotenv twice?

我可以在单个 运行 脚本中调用两次 load_dotenv 吗?

我想同时连接到两个 Auth0 租户。

from pathlib import Path
from os import environ as env
from dotenv import load_dotenv

from auth0.v3.authentication import GetToken
from auth0.v3.management import Auth0
from auth0.v3.exceptions import Auth0Error

import constants


def connect_to_auth0(environment):
    env_file = '.env.' + environment
    env_path = Path('.') / env_file
    load_dotenv(env_path)
    auth0_client_id = env[constants.AUTH0_CLIENT_ID]
    auth0_client_secret = env[constants.AUTH0_CLIENT_SECRET]
    auth0_domain = env[constants.AUTH0_DOMAIN]
    mgmt_api_url = 'https://'+auth0_domain+'/api/v2/'

    get_token = GetToken(auth0_domain)
    token = get_token.client_credentials(auth0_client_id,
                                         auth0_client_secret,
                                         mgmt_api_url)
    mgmt_api_token = token['access_token']
    return Auth0(auth0_domain, mgmt_api_token)


def main():
    tenant_1 = connect_to_auth0('tenant_1')
    tenant_2 = connect_to_auth0('tenant_2')

并且有一个 .env.tenant_1.env.tenant_2,每个租户都有适当的参数。 tenant_1tenant_2 是不同的 python 对象,但都引用租户 1。

我想你想要 dotenv_values 而不是 load_dotenv,这样你就可以得到一个 dict 而不是更新环境。 (我假设您未定义的全局 env 来自 from os import environ as env 之类的东西?)

def connect_to_auth0(environment):
    env_file = '.env.' + environment
    env_path = Path('.') / env_file
    env = dotenv_values(env_path)
    auth0_client_id = env[constants.AUTH0_CLIENT_ID]
    auth0_client_secret = env[constants.AUTH0_CLIENT_SECRET]
    auth0_domain = env[constants.AUTH0_DOMAIN]
    mgmt_api_url = 'https://'+auth0_domain+'/api/v2/'

    get_token = GetToken(auth0_domain)
    token = get_token.client_credentials(auth0_client_id,
                                         auth0_client_secret,
                                         mgmt_api_url)
    mgmt_api_token = token['access_token']
    return Auth0(auth0_domain, mgmt_api_token)