haps icon indicating copy to clipboard operation
haps copied to clipboard

Allow resolving configuration values from arbitrary sources

Open JosXa opened this issue 5 years ago • 0 comments

In order to make use of the awesome python-decouple library in conjunction with haps, I wrote the following monkeypatch:

from typing import Any

import decouple
from haps.config import Configuration
from haps.exceptions import UnknownConfigVariable


def decouple_resolver(self: Configuration, var_name: str) -> Any:
    """
    Monkeypatched resolver for using python-decouple together with haps.
    Gives priority to explicitly-declared resolvers in the application, then falls back to retrieving the value
    from decouple.
    """
    if var_name in self.resolvers:
        return self.resolvers[var_name]()
    env_var = decouple.config(var_name)
    if env_var:
        return env_var
    raise UnknownConfigVariable(f"No resolver registered for {var_name}")

# Override haps default resolver
Configuration._resolve_var = decouple_resolver

It occured to me that it would be nice to be able to provide custom variable resolvers for arbitrary keys (not just specified ones) to haps which it will use in a configurable lookup order (aka priority). The advantage of using decouple is that it already searches in a bunch of settings repositories (.env, settings.ini, env vars) and so simply adding it as a fallback is enough, but people might also want to add their own settings sources (some YAML or JSON files or whatever).

JosXa avatar Mar 02 '20 21:03 JosXa