environs is a Python library for parsing environment variables.
It allows you to store configuration separate from your code, as per
The Twelve-Factor App methodology.
# export TTL=-2
# export NODE_ENV='invalid'
# export EMAIL='^_^'
from environs import env, validate, ValidationError
# built-in validators (provided by marshmallow)
env.str(
"NODE_ENV",
validate=validate.OneOf(
["production", "development"], error="NODE_ENV must be one of: {choices}"
),
)
# => Environment variable "NODE_ENV" invalid: ['NODE_ENV must be one of: production, development']
# multiple validators
env.str("EMAIL", validate=[validate.Length(min=4), validate.Email()])
# => Environment variable "EMAIL" invalid: ['Shorter than minimum length 4.', 'Not a valid email address.']
# custom validator
def validator(n):
if n <= 0:
raise ValidationError("Invalid value.")
env.int("TTL", validate=validator)
# => Environment variable "TTL" invalid: ['Invalid value.']
environs.validate is equivalent to marshmallow.validate, so you can use any of the validators provided by that module.
Deferred validation
By default, a validation error is raised immediately upon calling a parser method for an invalid environment variable.
To defer validation and raise an exception with the combined error messages for all invalid variables, pass eager=False to Env.
Call env.seal() after all variables have been parsed.
# export TTL=-2
# export NODE_ENV='invalid'
# export EMAIL='^_^'
from environs import Env
from marshmallow.validate import OneOf, Email, Length, Range
env = Env(eager=False)
TTL = env.int("TTL", validate=Range(min=0, max=100))
NODE_ENV = env.str(
"NODE_ENV",
validate=OneOf(
["production", "development"], error="NODE_ENV must be one of: {choices}"
),
)
EMAIL = env.str("EMAIL", validate=[Length(min=4), Email()])
env.seal()
# environs.EnvValidationError: Environment variables invalid: {'TTL': ['Must be greater than or equal to 0 and less than or equal to 100.'], 'NODE_ENV': ['NODE_ENV must be one of: production, development'], 'EMAIL': ['Shorter than minimum length 4.', 'Not a valid email address.']}
env.seal() validates all parsed variables and prevents further parsing (calling a parser method will raise an error).
URL schemes
env.url() supports non-standard URL schemes via the schemes argument.
Some values should not be stored in the environment. For this use case a commonly
used technique is to store the value (e.g., a password) in a file and set the path
to that file in an environment variable. Use FileAwareEnv in place of Env to automatically check for environment variables with the _FILE suffix. If the
file is found, its contents will be read and returned.
To strip leading and trailing whitespaces from the value:
from environs import FileAwareEnv
# printf ' value with leading and trailing whitespaces \n' >/run/secrets/password
# export PASSWORD_FILE=/run/secrets/password
env: FileAwareEnv = FileAwareEnv(strip_whitespace=True)
password: str = env.str("PASSWORD") # => `value with leading and trailing whitespaces`
Defining custom parser behavior
# export DOMAIN='http://myapp.com'
# export COLOR=invalid
from furl import furl
# Register a new parser method for paths
@env.parser_for("furl")
def furl_parser(value):
return furl(value)
domain = env.furl("DOMAIN") # => furl('https://myapp.com')
# Custom parsers can take extra keyword arguments
@env.parser_for("choice")
def choice_parser(value, choices):
if value not in choices:
raise environs.EnvError("Invalid!")
return value
color = env.choice("COLOR", choices=["black"]) # => raises EnvError
Usage with Flask
# myapp/settings.py
from environs import Env
env = Env()
env.read_env()
# Override in .env for local development
DEBUG = env.bool("FLASK_DEBUG", default=False)
# SECRET_KEY is required
SECRET_KEY = env.str("SECRET_KEY")
Load the configuration after you initialize your app.
# myapp/app.py
from flask import Flask
app = Flask(__name__)
app.config.from_object("myapp.settings")
For local development, use a .env file to override the default
configuration.
# .env
DEBUG=true
SECRET_KEY="not so secret"
Note: Because environs depends on python-dotenv,
the flask CLI will automatically read .env and .flaskenv files.
Usage with Django
environs includes a number of helpers for parsing connection URLs. To
install environs with django support:
pip install environs[django]
Use env.dj_db_url, env.dj_cache_url and env.dj_email_url to parse the DATABASE_URL, CACHE_URL
and EMAIL_URL environment variables, respectively.
For more details on URL patterns, see the following projects that environs is using for converting URLs.
While os.environ is enough for simple use cases, a typical application
will need a way to manipulate and validate raw environment variables.
environs abstracts common tasks for handling environment variables.
environs will help you
cast envvars to the correct type
specify required envvars
define default values
validate envvars
parse list and dict values
parse dates, datetimes, and timedeltas
parse expanded variables
serialize your configuration to JSON, YAML, etc.
Why another library?
There are many great Python libraries for parsing environment variables.
In fact, most of the credit for environs' public API goes to the
authors of envparse and
django-environ.
environs aims to meet three additional goals:
Make it easy to extend parsing behavior and develop plugins.
Leverage the deserialization and validation functionality provided
by a separate library (marshmallow).
Clean up redundant API.
See this GitHub
issue
which details specific differences with envparse.
License
MIT licensed. See the
LICENSE file
for more details.
Alternatives
Use instead of environs: tools that do the same job, closest first.