Environment Variables

Environment variables are dynamic values that can affect the way running processes behave on a computer system. They are part of the operating system environment in which a process runs and are used by applications to determine various settings and configurations.

Environment files which has ‘.env’ extensions contains environment variables.

Sample env file:

Environment Variables Provides:

  • Configuration Management: The .env file serves as a centralized location to store configuration settings for your project without hardcoding.
  • Environment-specific Configuration: Environment files enable you to define different configuration settings for different environments
  • Security & Sensitive Information: Environment files providesa store sensitive information, such as access tokens, API keys, credentials, and outside of your codebase without tracking git.
  • Easy Deployment: Environment files provides quick deployment across different environments.
  • Git Ignore: Env files can ignore from version control systems (git) that provides protection of credentials.
  • Simplicty : You can access any defined environment variables inside of your codebase without export your variable from module.
  • Clean & Maintainable Code: Env Variables provides clean code that not hard-coding your frequently changing variables.

Usage of Env Files

1. Install python module by using pip installer:

2. Create .env file and add your variables key-pair format:

3. Import Dependencies:

4. Load Environment Variables from .env file:

To use env variables we need to load first.

load_dotenv() is a function that returns bool.

if .env variable is not exists in the path or env file is blank it returns false. So we can check env file existence quick.

5. Get env variable from .env file :

After we load environment variables from .env file we can access env variable by using getenv() function.

We can easily access and get env variable by using getenv() function.

Set Default Value

If there is no defined “user” or “password” variable, getenv(“user”, “default_value”) function’s second parameters sets default value. If there is no default_value function will return None.

Ignore from GIT

To prevent tracking credentials from git you should add your .env file into .gitignore that provides share-protection your files from 3th version control systems.

ibrahim tunc
ibrahim tunc
Articles: 13

Leave a Reply

Your email address will not be published. Required fields are marked *