Skip to main content

Type safe environment variables parsing.

Project description

MyENV: Environment Variable Parsing using Type annotations

MyENV parses you're environment variables using type annotations. This allows you to configure your app/service as layed out by 12factor.net/config, while keeping your code type safe.

Project/Repo:

MIT License Supported Python Versions PyCalVer v201902.0007 PyPI Version PyPI Downloads

Code Quality/CI:

Build Status Type Checked with mypy Code Coverage Code Style: sjfmt

Name role since until
Manuel Barkhau (mbarkhau@gmail.com) author/maintainer 2018-09 -

Environment Variables and Configuration

In order of priority, configuration is parsed from

  1. Environment variables
  2. Configuration files
  3. Defaults defined in source code

Declaration

The myenv module provides a convenient way to do this parsing. As far as your application code is concerned, it is enough to declare a subclass of myenv.BaseEnv. Instances of this subclass are populated from config files and the environment.

import myenv


class Database(myenv.BaseEnv):

    _environ_prefix = "DATABASE_"

    vendor    : str  = "postgres"
    host      : str  = "127.0.0.1"
    port      : int  = 5432
    user      : str  = "myuser"
    password  : str
    name      : str  = "app_db_v1"

    @property
    def url(self) -> str:
        db = self
        return f"{db.vendor}://{db.user}:{db.password}@{db.host}:{db.port}/{db.name}"

For each annoatated member of DBEnv declare the 1. name, 2. type and 3. an optional default variable. Members without a default must be set by an environment variable or configuration file, otherwise a KeyError will be raised.

Parsing

To use the above configuration class, simply instanciate it.

# my_service/cfg.py
import sqlalchemay as sqla

db_cfg = Database()     # populated from os.environ
db_cfg.port             # 12345          (parsed from DATABASE_PORT)
db_cfg.password         # "supersecret"  (parsed from DATABASE_PASSWORD)
db_cfg.url              # "mysql://myuser:supersecret@127.0.0.1:12345/mydb"

engine = sqla.create_engine(db_cfg.url)

In case you're worried about the instantiation of Database(), it will return a singleton instance, so the os.environ and configuration files are parsed only once.

Config Files

When parsing configs, the following paths are parsed if they exist. By default the configs are loaded from ${PWD}/config/, but you can override the location of configuration files by setting the environment variable ENV_CONFIG_DIR.

  • ${ENV_CONFIG_DIR}/${ENV}.env
  • ${ENV_CONFIG_DIR}/prod.env

Any variables defined in these files will be set, unless it was already set in the environ or a previous config file.

This approach allows you to satisfy typical use cases in which a service is hosted:

  1. Development Machine
  2. Stage/Production Environment

You can put use case specifc configuration files in your project source tree, such as:

  • project/config/dev.env
  • project/config/stage.env
  • project/config/prod.env

To parse the appropriate config file, all you have to do is set a single environment variable ENV=<envname>. If ENV is not set, it will fall back to ENV=prod.

The *.env config files are flat text files, with one KEY=value mapping per line. The only lines which are parsed, are lines which begin with an all upper case token, followed by an = character:

# config/prod.env
DATABASE_PORT=12345
DATABASE_USER=prod_user
DATABASE_NAME=prod_db
DATABASE_PASSWORD=supersecret

For sensitive configuration parameters, such as passwords and authentication tokens, you may prefer to write config files outside of your source tree, or to provide them always and only via environment variables.

Changelog for https://gitlab.com/mbarkhau/myenv

v201902.0007

  • Packaging updates
  • Better test and mypy coverage

v201812.0005-beta

v201809.0001-beta

  • Initial release

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

myenv-201902.7.tar.gz (11.0 kB view details)

Uploaded Source

Built Distribution

myenv-201902.7-py36.py37-none-any.whl (8.6 kB view details)

Uploaded Python 3.6 Python 3.7

File details

Details for the file myenv-201902.7.tar.gz.

File metadata

  • Download URL: myenv-201902.7.tar.gz
  • Upload date:
  • Size: 11.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.6.3 requests-toolbelt/0.8.0 tqdm/4.29.1 CPython/3.6.8

File hashes

Hashes for myenv-201902.7.tar.gz
Algorithm Hash digest
SHA256 739c0ed411fc8a9c24b07f7834edcaaeeac994fff0e6da9d711d10e327225fef
MD5 12cb17e7b8d4c01e21f5ed916d3c5e24
BLAKE2b-256 5a86daccc488c93c0a187da3dd929896c375b156ee8f25adb3c015d800e18a22

See more details on using hashes here.

File details

Details for the file myenv-201902.7-py36.py37-none-any.whl.

File metadata

  • Download URL: myenv-201902.7-py36.py37-none-any.whl
  • Upload date:
  • Size: 8.6 kB
  • Tags: Python 3.6, Python 3.7
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.6.3 requests-toolbelt/0.8.0 tqdm/4.29.1 CPython/3.6.8

File hashes

Hashes for myenv-201902.7-py36.py37-none-any.whl
Algorithm Hash digest
SHA256 530cf9c08d4e7361421705143b02b527964386343777029c96c3163c87b3752f
MD5 4034a6cf114211aca9897f104be393e6
BLAKE2b-256 da48977e0e54ba6bfad865b6195026a0c2125b0bef022e10f1687662cd96bb32

See more details on using hashes here.

Supported by

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