Skip to main content
In modern application development, it’s crucial to avoid hardcoding sensitive information—such as database credentials and secret keys—directly in your code. Hardcoding makes your application vulnerable to security risks, especially when code is shared or pushed to public repositories like GitHub. Moreover, it complicates deployment across multiple environments (development, staging, production). This guide covers best practices for managing environment variables, ensuring your application remains secure and adaptable.

The Risks of Hardcoding

Embedding sensitive data directly in your source code exposes it to unnecessary risk and limits flexibility. Consider the following Python code snippet:
Hardcoding the database URL leads to two significant problems:
  1. If the code is pushed to a public repository, your credentials are exposed to…
If the code is pushed to a public repository, your credentials are exposed to everyone.
  1. The static configuration ties the code to a single environment, forcing manua…
The static configuration ties the code to a single environment, forcing manual updates for production deployments.
Similarly, hardcoding OAuth secret keys can lead to security vulnerabilities. For example:
Hardcoding secret keys makes it difficult to manage configurations across different environments, increasing security risks and maintenance overhead.

Leveraging Environment Variables

Environment variables allow you to externalize sensitive configuration details. By setting these values at the operating system level, your application can automatically retrieve the correct configuration for the current environment.

Accessing Environment Variables in Python

Create a simple file (e.g., example.py) to demonstrate accessing an environment variable:
Execute the script with:
This command prints the value of the PATH variable, illustrating how environment variables can be accessed in Python.

Configuring Environment Variables

On Windows

  1. Open Advanced System Settings and click Environment Variables.
  2. Create a new user variable (e.g., MY_DB_URL) with a value like localhost:5432.
  3. Open a new command prompt, then verify by running:
Note: If you update environment variables, close and reopen your terminal or VS Code to see the changes.

On macOS/Linux

Set an environment variable in the terminal:
Or verify using:

Managing Multiple Variables with .env Files

For projects with numerous environment variables, managing them manually can be tedious. A common solution during development is to use an environment file (commonly named .env).

Using Pydantic BaseSettings for Validation

Pydantic offers a robust solution for managing and validating environment variables through the BaseSettings class. This method ensures that all required settings are present and automatically handles type conversions. Create a configuration file (e.g., config.py):
Pydantic reads and validates the environment variables at runtime. If a required variable is missing or a conversion fails, it raises a descriptive error.

Creating the .env File

In your project root, add a .env file:
Avoid committing your .env file to version control. Add .env to your .gitignore to protect your sensitive data.

Integrating Environment Variables into Your Application

After centralizing your configuration using environment variables, update your codebase to reference these settings.

Database Connection Setup

In database.py, adjust your database connection configuration to use environment variables:

OAuth2 Token Configuration

Similarly, update your OAuth2 settings to reference configuration variables:
By centralizing configuration in config.py, your application automatically adapts to different environments without modifying the code.

Summary

  • Avoid Hardcoding: Embed sensitive information as environment variables rather than hardcoding.
  • Environment Variables: Utilize OS-level variables to manage configurations dynamically.
  • Pydantic Validation: Employ Pydantic’s BaseSettings to validate and manage environment settings.
  • .env File Usage: During development, use a .env file to simplify configuration management, but exclude it from version control.
  • Dynamic Application Configuration: Update your application to utilize environment variables, ensuring secure and flexible deployments across various environments.
By following these practices, you improve your application’s security, scalability, and maintainability while reducing the risk of exposing sensitive information.

Watch Video