Passed
Branch master (918acb)
by Steve
02:15
created

lagom.environment.Env.__init__()   A

Complexity

Conditions 3

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
cc 3
eloc 10
nop 2
dl 0
loc 13
ccs 5
cts 6
cp 0.8333
crap 3.0416
rs 9.9
c 0
b 0
f 0
1
"""
2
This module provides code to automatically load environment variables from the container.
3
It is built on top of (and requires) pydantic.
4
5
At first one or more classes representing the required environment variables are defined.
6
All environment variables are assumed to be all uppercase and are automatically lowercased.
7
8
class MyWebEnv(Env):
9
    port: str
10
    host: str
11
12
class DBEnv(Env):
13
    db_host: str
14
    db_password: str
15
16
17
@bind_to_container(c)
18
def some_function(env: DBEnv):
19
    do_something(env.db_host, env.db_password)
20
21
"""
22 1
import os
23 1
from abc import ABC
24 1
from typing import ClassVar, Optional
25
26 1
try:
27 1
    from pydantic.main import BaseModel
28
except ImportError as error:
29
    raise ImportError(
30
        "Using Env requires pydantic to be installed. Try `pip install lagom[env]`"
31
    ) from error
32
33
34 1
class Env(ABC, BaseModel):
35
    """
36
    This class implements logic to automatically load properties from ENV
37
    variables.
38
    """
39
40 1
    PREFIX: ClassVar[Optional[str]] = None
41
42 1
    def __init__(self, **kwargs):
43 1
        if len(kwargs) == 0:
44 1
            prefix = f"{self.PREFIX}_" if self.PREFIX else ""
45 1
            envs = os.environ.items()
46 1
            super().__init__(
47
                **{
48
                    key.replace(prefix, "").lower(): value
49
                    for (key, value) in envs
50
                    if key.startswith(prefix)
51
                }
52
            )
53
        else:
54
            super().__init__(**kwargs)
55