Wraps python-dotenv to enable
switching among multiple, environment-specific .env files.
The fastest, easiest way to use dotenv_switch is to use the auto mode to
automatically load dotenv files upon import: import dotenv_switch.auto
Example:
# Assuming $APP_ENV=prod and .env.prod contains
# A_VARIABLE=itsvalue
import dotenv_switch.auto
import os
os.getenv('A_VARIABLE')
>> itsvalueThe auto mode accepts all defaults:
APP_ENVis the name of the environment variable that specifies the application environment.- Load
.env.$APP_ENVif it exists. - If
.env.$APP_ENVdoes not exist, fallback to loading.env.test, or if that doesn't exist,.env. - If none of the above files exist, return successfully and raise no errors/exceptions.
For instructions on overriding the defaults, see API.
import dotenv_switch
dotenv_switch.load(var='APP_ENV', fallbacks=['.env.test','.env'], required=False, usecwd=False, **kwargs)
Parameters:
var(str, optional) name of the env var specifying the desired environemnt (default isAPP_ENV)fallbacks(list, optional) list of dotenv filenames to use ifvarisNoneor.env.{var}is not found (default is['.env.test','.env'])required(bool, optional) whether to raise an exception if no dotenv file is found (default isFalse)usecwd(bool, optional)dotenv.find_dotenv()param, with the same default, which will be passed to that function (default isFalse)**kwargs(optional) any remaining params will be passed todotenv.load_dotenv()
Raises:
DotenvSwitchUnspecifiedFilesRequiredErrorIf required isTrue, butvarisNoneor.env.{var}cannot be found, and fallbacks isNoneor empty.DotenvSwitchFileNotFoundErrorIfrequiredisTruebut no dotenv file can be found.
Returns
DotEnv, the object returned bydotenv.loadenv().
The default values of load parameters are specified by these package variables:
default_var = 'APP_ENV'
default_fallbacks = ['.env.test', '.env']
default_required = False
default_usecwd = False
Resetting these package variables is another way to customize the behavior of load().
dotenv_switch.auto just calls dotenv_switch.load() after importing the package.
Overriding load() parameters and/or resetting package variable defaults allows for
easy creation of custom auto modes for convenient, one-line importing and loading.
$ poetry run pytest