InfoScout GarlicConfig
Project description
GarlicConfig
GarlicConfig is a framework that makes it easy to write complex configurations with ability to validate them easily.
You can define models by inheriting from ConfigModel
:
from garlicconfig import models
class DatabaseConfig(models.ConfigModel):
pass
For properties, you can use ConfigField
. There are a set of built-in fields:
- StringField
- IntegerField
- ArrayField
- ModelField
- BooleanField
You can also make your own custom ConfigModel
and/or ConfigField
.
for example:
from garlicconfig import fields
from garlicconfig.exceptions import ValidationError
class EvenIntegerField(IntegerField):
def validate(self, value):
if value % 2 != 0:
raise ValidationError('bad integer')
def to_model_value(self, value):
return int(value)
def to_dict_value(self, value):
return str(value)
The field class above stores str in the python dictionary representation. However, for the materialized config model, integer is used. It also invalidates unaccepted values, in this case odd values.
for example:
class SomeRandomConfig(ConfigModel):
value = EvenIntegerField(nullable=False, default=2)
You can use get_dict
method on config models to get a python dictionary with basic value types in it. This is handy to cache it in memory, or to use it for serialization.
load_dict
will create a new config model from a python dictionary.
Serialization
You can use the following code to encode/decode configs. The default encoder is Json. However, you can write your own encoder and support other formats as needed.
from garlicconfig import encoder
config = DatabaseConfig()
serialized_string = encoder.encode(config, pretty=True)
# You must provide the config class.
config = encoder.decode(serialized_string, DatabaseConfig)
Merging layers
You merge two configuration layers in order to support inheritance. Python dict
will get merged but other values will be overridden.
for example:
from garlicconfig.utils import merge
config_dict1 = {
'name': 'Peyman',
'numbers': [1, 2, 3]
'extra': {
'has_id': True
}
}
config_dict2 = {
'name': 'Patrick',
'numbers': [4, 5, 6]
'extra': {
'has_degree': True
}
}
# this will create a copy of base including config_dict2's data
merge(base=config_dict1, config=config_dict2)
# that will give you the following object.
{
'name': 'Patrick',
'numbers': [4, 5, 6],
'extra': {
'has_degree': True,
'has_id': True
}
}
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for garlicconfig-1.0.6-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2c324114331600e04de55936ca2e134eb78ee55ab36922ba7e64fe41095b8546 |
|
MD5 | 56f61088af7f319dccab5f01d2426593 |
|
BLAKE2b-256 | a610faf6804da6ca68579a23f1666a2b304ea11ba4781becdcf1af84affaf8ad |