44"""
55
66import os
7- from typing import Any , Optional , NoReturn
7+ from collections .abc import Callable
8+
9+ from distutils .util import strtobool
10+ from typing import Any , Type
811
912from kirovy import exceptions
1013from kirovy .typing import SettingsValidationCallback
1114from kirovy .settings import settings_constants
1215
1316MINIMUM_SECRET_KEY_LENGTH = 32
17+ _NOT_SET = object ()
18+
19+
20+ def _unvalidated_env_var (_ : str , __ : Any ) -> None :
21+ return
1422
1523
1624def get_env_var (
1725 key : str ,
18- default : Optional [Any ] = None ,
19- validation_callback : Optional [SettingsValidationCallback ] = None ,
26+ default : Any | None = _NOT_SET ,
27+ validation_callback : SettingsValidationCallback = _unvalidated_env_var ,
28+ * ,
29+ value_type : Type [Callable [[object ], Any ]] = str ,
2030) -> Any :
2131 """Get an env var and validate it.
2232
@@ -25,16 +35,24 @@ def get_env_var(
2535
2636 Do not provide defaults for e.g. passwords.
2737
28- :param str key:
38+ :param key:
2939 The env var key to search for.
30- :param Optional[Any] default:
40+ :param default:
3141 The default value. Use to make an env var not raise an error if
3242 no env var is found. Never use for secrets.
3343 If you use with ``validation_callback`` then make sure your default value will
3444 pass your validation check.
35- :param Optional[SettingsValidationCallback] validation_callback:
45+ :param validation_callback:
3646 A function to call on a value to make sure it's valid.
3747 Raises an exception if invalid.
48+ :param value_type:
49+ Convert the string from ``os.environ`` to this type. The type must be callable.
50+ No validation is performed on the environment string before attempting to cast,
51+ so you're responsible for handling cast errors.
52+
53+ .. note::
54+
55+ If you provide ``bool`` then we will use ``distutils.util.strtobool``.
3856 :return Any:
3957 The env var value
4058
@@ -45,28 +63,29 @@ def get_env_var(
4563
4664 """
4765
48- value : Optional [Any ] = os .environ .get (key )
49-
50- if value is None :
51- value = default
66+ value : str | None = os .environ .get (key )
5267
53- if value is None :
68+ if value is None and default is _NOT_SET :
5469 raise exceptions .ConfigurationException (key , "Env var is required and cannot be None." )
5570
56- if validation_callback is not None :
57- validation_callback (key , value )
71+ if value_type == bool :
72+ value_type = strtobool
73+
74+ value = value_type (value ) if value is not None else default
75+
76+ validation_callback (key , value )
5877
5978 return value
6079
6180
62- def secret_key_validator (key : str , value : str ) -> NoReturn :
81+ def secret_key_validator (key : str , value : str ) -> None :
6382 """Validate the secret key.
6483
6584 :param str key:
6685 env var key.
6786 :param str value:
6887 The value found.
69- :return NoReturn :
88+ :return:
7089
7190 :raises exceptions.ConfigurationException:
7291 """
0 commit comments