pythondjangopython-decouple

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?


Solution

  • 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))