Skip to content Skip to sidebar Skip to footer

How Do You Use Python-decouple To Load A .env File Outside The Expected Paths?

I'm forced to keep my .env file in a non-standard path outside the root of my project (in a separate directory altogether). Let's say I have my Django project in /var/projects/my_p

Solution 1:

I figured it out.

Instead of importing decouple.config and doing the usual config('FOOBAR'), create a new decouple.Config object using RepositoryEnv('/path/to/env-file').

from decouple import Config, RepositoryEnv

DOTENV_FILE = '/opt/envs/my-project/.env'
env_config = Config(RepositoryEnv(DOTENV_FILE))

# use the Config().get() method as you normally would since 
# decouple.config uses that internally. 
# i.e. config('SECRET_KEY') = env_config.get('SECRET_KEY')
SECRET_KEY = env_config.get('SECRET_KEY')

Hopefully this helps someone.

Solution 2:

If you look at the decouple implementation, config is just a pre-instantiated AutoConfig:

config = AutoConfig()

But AutoConfig takes as optional argument search_path so we can do the following:

from decouple importAutoConfigconfig= AutoConfig(search_path='/opt/envs/my-project')

Then you can do as usual:

secret_key = config('SECRET_KEY')

Solution 3:

Now, django-decouple==2.1 supports having settings.ini and .env files in any parent directory of the project dir.

(And the old methods don't work anymore. - from decouple import Config, RepositoryEnv does not work, AutoConfig does not have search_path as parameter.)

This is convenient because you would want to keep the settings.ini in the project folder on your local machine and you would want to have clean checkouts on the staging/prod server, thus the settings.ini is better located outside the project folder.

Post a Comment for "How Do You Use Python-decouple To Load A .env File Outside The Expected Paths?"