Skip to main content

A robust Python library for managing environment variables with .env files, ensuring they are all present and correctly configured.

Project description

py-dotenv-safe

Effortlessly load and verify all your environment variables from .env files, ensuring they are all present and correctly configured.

py-dotenv-safe ensures that all required environment variables are defined after reading from .env. The names of the required variables are read from .env.example, which should be committed along with your project.

Installation

You can install the library using pip:

pip install py-dotenv-safe

Getting Started

To start using py-dotenv-safe, follow these steps:

  1. Create .env and .env.example Files: Ensure you have both .env and .env.example files in your project repository.

  2. Use the Library in Your Code: Import the library and configure it to load your environment variables.

Usage

Here is a basic example of how to use the library:

from py_dotenv_safe import config

options = {
    "dotenvPath": ".env",        # Path to the environment file
    "examplePath": ".env.example", # Path to the example environment file
    "allowEmptyValues": False,   # Set to True if you want to allow empty values
}

try:
    config(options)
    print("Environment variables loaded successfully.")
except Exception as e:
    print(f"Error: {e}")

Configuration Options

  • dotenvPath (str): Path to the .env file.
  • examplePath (str): Path to the .env.example file.
  • allowEmptyValues (bool): Whether to allow empty values. Defaults to False.

Example

Assume you have the following .env file:

DATABASE_URL=postgres://user:password@localhost:5432/mydatabase
SECRET_KEY=mysecretkey

And an .env.example file:

DATABASE_URL=
SECRET_KEY=

Using the config function ensures that all required environment variables are present and correctly configured. If any variables are missing, a MissingEnvVarsError will be raised, indicating which variables are missing.

Handling Missing Variables

If your provided .env file does not contain all the variables defined in .env.example, an exception is thrown:

MissingEnvVarsError: The following variables were defined in .env.example but are not present in the environment:
  TOKEN, KEY
Make sure to add them to .env or directly to the environment.

If you expect any of these variables to be empty, you can use the allowEmptyValues option:
config({"allowEmptyValues": True})

Not all the variables have to be defined in .env; they can be supplied externally. For example, the following would work:

$ python config.py

Advanced Usage

Requiring and loading is identical:

from dotenv_safe import config

config({
    "dotenvPath": ".env",
    "examplePath": ".env.example",
    "allowEmptyValues": False,
})

This will load environment variables from .env as usual, but will also read any variables defined in .env.example. If any variables are already defined in the environment before reading from .env, they will not be overwritten. If any variables are missing from the environment, a MissingEnvVarsError will be thrown, which lists the missing variables. Otherwise, returns an object with the following format:

{
  "parsed": {"SECRET": "topsecret", "TOKEN": ""},          # parsed representation of .env
  "required": {"SECRET": "topsecret", "TOKEN": "external"} # key-value pairs required by .env.example and defined by environment
}

Continuous Integration (CI)

It can be useful to depend on a different set of example variables when running in a CI environment. For example:

from dotenv_safe import config

config({
    "examplePath": ".env.ci"
})

Options

All options supported by dotenv are also supported by py-dotenv-safe, in addition to the options below:

config({
    "dotenvPath": ".env",
    "allowEmptyValues": True,
    "examplePath": "./.my-env-example-filename"
})

Starting from version 1.0.0, dotenv is a peer dependency of py-dotenv-safe. This means that the actual version of dotenv used defaults to the latest available at install time, or whatever is specified by your application.

allowEmptyValues

If a variable is defined in the example file and has an empty value in the environment, enabling this option will not throw an error after loading. Defaults to False.

examplePath

Path to the example environment file. Defaults to .env.example.

dotenvPath

Path to the environment file. Defaults to .env.

Motivation

I regularly use apps that depend on .env files but don't validate if all the necessary variables have been defined correctly. Instead of having to document and validate this manually, I prefer to commit a self-documenting .env.example file that may have placeholder or example values filled in. This can be used as a template or starting point for an actual .env file.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py_dotenv_safe-1.0.1.tar.gz (9.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

py_dotenv_safe-1.0.1-py3-none-any.whl (7.5 kB view details)

Uploaded Python 3

File details

Details for the file py_dotenv_safe-1.0.1.tar.gz.

File metadata

  • Download URL: py_dotenv_safe-1.0.1.tar.gz
  • Upload date:
  • Size: 9.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.0 CPython/3.12.1

File hashes

Hashes for py_dotenv_safe-1.0.1.tar.gz
Algorithm Hash digest
SHA256 1ca96558bd3195d706db1ed73fb8bc2cc1f14140ecc371c7022b9b512c4dc9b3
MD5 367a349c18690a7e54e58083437bd46e
BLAKE2b-256 3387922b3d889f2be12de3925dd880f72c1b17bd71f12dc2efce91d1c9c57b6b

See more details on using hashes here.

File details

Details for the file py_dotenv_safe-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: py_dotenv_safe-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 7.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.0 CPython/3.12.1

File hashes

Hashes for py_dotenv_safe-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f2de7b8fdce6aad4cfa574f54efc113c768e9bf5ac094f118d1b58f3ba445b00
MD5 64c967d5afc9dfc2c9c52484d1b47157
BLAKE2b-256 1d99e4dbec99dda0e570f3b550bf884af0784c9eb37a2c62e342c36bb78673e8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page