1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
|
"""
Functions to read values directly from a
:class:`staticconf.config.ConfigNamespace`. Values will be validated and
cast to the requested type.
Examples
--------
.. code-block:: python
import staticconf
# read an int
max_cycles = staticconf.read_int('max_cycles')
start_id = staticconf.read_int('poller.init.start_id', default=0)
# start_date will be a datetime.date
start_date = staticconf.read_date('start_date')
# matcher will be a regex object
matcher = staticconf.read_regex('matcher_pattern')
# Read a value from a different namespace
intervals = staticconf.read_float('intervals', namespace='something')
Readers can be attached to a namespace using a :class:`NamespaceReaders`
object.
.. code-block:: python
import staticconf
bling_reader = staticconf.NamespaceReaders('bling')
# These values are read from the `bling` ConfigNamespace
currency = bling_reader.read_string('currency')
value = bling_reader.read_float('value')
Arguments
---------
Readers accept the following kwargs:
config_key
string configuration key using dotted notation
default
if no `default` is given, the key must be present in the configuration.
If the key is missing a :class:`staticconf.errors.ConfigurationError`
is raised.
namespace
get the value from this namespace instead of DEFAULT.
Building custom readers
-----------------------
:func:`build_reader` is a factory function which can be used for creating
custom readers from a validation function. A validation function should handle
all exceptions and raise a :class:`staticconf.errors.ValidationError` if there
is a problem.
First create a validation function
.. code-block:: python
def validate_currency(value):
try:
# Assume a tuple or a list
name, decimal_points = value
return Currency(name, decimal_points)
except Exception, e:
raise ValidationErrror(...)
Example of a custom reader:
.. code-block:: python
from staticconf import readers
read_currency = readers.build_reader(validate_currency)
# Returns a Currency object using the data from the config namespace
# at they key `currencies.usd`.
usd_currency = read_currency('currencies.usd')
"""
from typing import Any
from typing import Callable
from typing import Dict
from typing import Iterator
from typing import Optional
from typing import Tuple
from typing import Type
from staticconf import validation, config, errors
from staticconf.config import ConfigNamespace
from staticconf.config import ConfigGetValue
from staticconf.proxy import ValueProxy
from staticconf.proxy import UndefToken
from staticconf.validation import Validator
import sys
if sys.version_info >= (3, 10):
from typing import Protocol
else:
from typing_extensions import Protocol
Builder = Callable[[Validator, str], ConfigGetValue]
def _read_config(
config_key: str,
config_namespace: ConfigNamespace,
default: Any
) -> Any:
value = config_namespace.get(config_key, default=default)
if value is UndefToken:
msg = '{} missing value for {}'.format(config_namespace, config_key)
raise errors.ConfigurationError(msg)
return value
def build_reader(
validator: Validator,
reader_namespace: str = config.DEFAULT,
) -> ConfigGetValue:
"""A factory method for creating a custom config reader from a validation
function.
:param validator: a validation function which acceptance one argument (the
configuration value), and returns that value casted to
the appropriate type.
:param reader_namespace: the default namespace to use. Defaults to
`DEFAULT`.
"""
class Reader(ConfigGetValue):
def __call__(
self,
config_key: str,
default: Any = UndefToken,
namespace: Optional[str] = None,
unsued: Optional[str] = None,
) -> ValueProxy:
config_namespace = config.get_namespace(namespace or reader_namespace)
return validator(_read_config(config_key, config_namespace, default))
return Reader()
class NameFactory(Protocol):
@staticmethod
def get_name(name: str) -> str:
...
@staticmethod
def get_list_of_name(validator_name: str) -> str:
...
class ReaderNameFactory:
@staticmethod
def get_name(name: str) -> str:
return 'read_%s' % name if name else 'read'
@staticmethod
def get_list_of_name(name: str) -> str:
return 'read_list_of_%s' % name
def get_all_accessors(
name_factory: Type[NameFactory],
) -> Iterator[Tuple[str, Validator]]:
for name, validator in validation.get_validators():
yield name_factory.get_name(name), validator
yield (name_factory.get_list_of_name(name),
validation.build_list_type_validator(validator))
class NamespaceAccessor:
def __init__(
self,
name: str,
accessor_map: Dict[str, Any],
builder: Builder,
) -> None:
self.accessor_map = accessor_map
self.builder = builder
self.namespace = name
def __getattr__(self, item: str) -> Any:
if item not in self.accessor_map:
raise AttributeError(item)
return self.builder(self.accessor_map[item], self.namespace)
def get_methods(self) -> Dict[str, Any]:
return {name: getattr(self, name) for name in self.accessor_map}
def build_accessor_type(
name_factory: Type[NameFactory],
builder: Builder,
) -> Callable[[str], NamespaceAccessor]:
accessor_map = dict(get_all_accessors(name_factory))
return lambda name: NamespaceAccessor(name, accessor_map, builder)
NamespaceReaders = build_accessor_type(ReaderNameFactory, build_reader)
"""An object with all reader functions which retrieve configuration from
a named namespace, instead of `DEFAULT`.
"""
default_readers = NamespaceReaders(config.DEFAULT)
globals().update(default_readers.get_methods())
__all__ = ['NamespaceReaders'] + list(default_readers.get_methods())
|