Skip to content

Cjkjvfnby/declared_env

Repository files navigation

Ruff Ruff

Declared env

I tired of collecting env variables in code to make a description and decide to write a helper library. I like to write code in declarative declare what you want and use it with benefits:

  • autocomplete: no more string literals around a file
  • enforce best practices: each variable has a prefix, all names in uppercase
  • error reports:, you got full report, if you missed something
  • help: get list of variables to make an instruction for admins

Array, dict and json types not supported. If you need complex structures probably environment is not the best way to configure your app.

All these flake8 plugins is a little overkill.

Platform independent.

Dependencies

Python3.9

Examples

Simple example

class MyEnv(EnvironmentDeclaration):
    prefix = "FOO"
    host = EnvironmentString(default="localhost")  # env: FOO_HOST

my_env = MyEnv()
my_env.host
# 'localhost'

Django example

class Environment(EnvironmentDeclaration):
    prefix = "MYSITE"
    secret_key = EnvironmentString(
        default="foo",
        help_text="see https://docs.djangoproject.com/en/3.0/ref/settings/#secret-key "
    )


ENVIRONMENT = Environment()  # make it in caps to use in `from django.conf import settings`

SECRET_KEY = ENVIRONMENT.secret_key

If you assign declaration into variable with name in caps, you can access it via settings. In that case to get list of environment variables you can create manage py command. Create a manage.py command to show help.

mysite/polls/management/commands/show_env.py

from django.conf import settings
from django.core.management.base import BaseCommand

from declared_env import EnvironmentDeclaration


class Command(BaseCommand):
    help = "Collect all env variables"

    def handle(self, *args, **options):
        for x in dir(settings):
            val = getattr(settings, x)
            if isinstance(val, EnvironmentDeclaration):
                print(val.get_help())
mysite> manage.py show_env
MYSITE_SECRET_KEY   see https://docs.djangoproject.com/en/3.0/ref/settings/#secret-key , default=foo

Or you can just run python settings.py and print help.

if __name__ == '__main__':
    print(ENVIRONMENT.get_help())

Development

Install dev requirements

pip install -r requirements-dev.txt

Install pre-commit

  • add hooks
    pre-commit install
    pre-commit install --hook-type commit-msg
  • update to the latest versions
    pre-commit autoupdate

Formatting and Linting

pre-commit run --all-files

Run test

pytest --cov=declared_env --cov-report html

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Languages