Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use different .env files with python-decouple

I am working on a django project that I need to run it with Docker. In this project I have multiples .env files: .env.dev, .env.prod, .env.staging. Is there a right way to manage all this file with the package python-decouple? I've search for a workaround to deal with this challenge and do not find any kind of answer, not even on the official documentation.

Can I use something like:

# dont works that way, it's just a dummie example
python manage.py runserver --env-file=.env.prod

or maybe any way to setting or override the file I need to use?

like image 487
Johnny Pereira Avatar asked Jul 30 '26 17:07

Johnny Pereira


2 Answers

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

from decouple import Config, RepositoryEnv

DOTENV_FILE = '/home/user/my-project/.env.prod'
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')
like image 166
Boro Avatar answered Aug 02 '26 07:08

Boro


Here's my implementation:

import os
import pathlib
import decouple
from decouple import RepositoryEnv

ENVIRONMENT = os.getenv("ENVIRONMENT", default="DEVELOPMENT")
def get_env_config() -> decouple.Config:
    """
    Creates and returns a Config object based on the environment setting.
    It uses .dev.env for development and .prod.env for production.
    """
    env_files = {
        "DEVELOPMENT": ".dev.env",
        "PRODUCTION": ".prod.env",
    }

    app_dir_path = pathlib.Path(__file__).resolve().parent.parent.parent
    env_file_name = env_files.get(ENVIRONMENT, ".dev.env")
    file_path = app_dir_path / env_file_name

    if not file_path.is_file():
        raise FileNotFoundError(f"Environment file not found: {file_path}")

    return decouple.Config(RepositoryEnv(file_path))

like image 45
Edward Chapman Avatar answered Aug 02 '26 06:08

Edward Chapman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!