Setting and Loading variables depending on environment

315 Views Asked by At

I need help on how to call specific variables depending on the environment. Currently, the project's root contains .env file that contains all environment variables being used by the project, but I need to load it according to environment

local -> where development happens
staging -> where we test our project
production -> where we deploy our final project

So in my project root, the goal is to use the file that contains specific values for variables depending on the environment where the [project runs. We have 3 files for the environment variables

local.env
    INTEGRATION_URL=http://sandbox.api.com
staging.env
    INTEGRATION_URL=http://sandbox2.api.com
production.env
    INTEGRATION_URL=http://production.api.com

So inside client.py

 from dotenv import load_dotenv
 load_dotenv(os.getenv('local.env'))

 class Client(BaseClient):
     def _init_(self):
          self.endpoint = os.environ.get('INTEGRATION_URL') // it should be `http://sandbox.api.com` if I run the project locally

But with this implementation, it still loads the default environment variables defined in the .env file. I need to remove the.env file and just used the 3 env files

Any help?

1

There are 1 best solutions below

0
On BEST ANSWER

I solved it by removing all variables in .env, and putting a new variable that would specify which file should be called

 .env
     ENV_PATH=local.env // or prod.env // or staging.env

Then in client.py

  from dotenv import load_dotenv
  load_dotenv(os.getenv('ENV_PATH'), 'prod.env')// default to prod if not set

  class Client(BaseClient):
     def _init_(self):
        self.endpoint = os.environ.get('INTEGRATION_URL')