Use with ConfigParser instance
[server]
host = 127.0.0.1
port = 80
import configparser
from confu.schema import Int, IpAddress, Schema, validate
# this schema describes the [server] section
class ServerSchema(Schema):
host = IpAddress()
port = Int(default=80)
# this schema describes the entire config
class ConfigSchema(Schema):
# server schema as sub schema
server = ServerSchema()
# read config
config = configparser.ConfigParser()
config.read("config.cfg")
# validate config
success, errors, warnings = validate(ConfigSchema(), config, log=print)
Examples with SettingsManager
import os
from confu.util import SettingsManager
# using local scope g
g = {}
settings_manager = SettingsManager(g)
settings_manager.set_option("TEST_SETTING", "world")
print(g["TEST_SETTING"])
# using Global scope
settings_manager = SettingsManager(globals())
settings_manager.set_option("TEST_SETTING", "world")
print(TEST_SETTING)
# setting from env
os.environ["ENV_SETTING"] = "my_setting" # setting env variable
settings_manager.set_from_env("ENV_SETTING")
print(ENV_SETTING)
# setting boolean
settings_manager.set_bool("BOOL_SETTING", False)
print(BOOL_SETTING)
# setting boolean overriden from env var from env
os.environ["ENV_BOOL"] = "True" # setting env variable
settings_manager.set_bool("ENV_BOOL", False)
print(ENV_BOOL)
# setting int from env
os.environ["ENV_INT"] = "123" # setting env variable
settings_manager.set_option("ENV_INT", None, envvar_type=int)
print(ENV_INT)
# setting default
settings_manager.set_default("DEFAULT_SETTING", "my_defualt")
print(DEFAULT_SETTING)
# include another file (./test.py)
settings_manager.try_include("./test.py")
print(EXTERNAL_SETTING)
File test.py
settings_manager.set_option("EXTERNAL_SETTING", "my_external")
Examples with Config
from confu.config import Config
from confu.schema import Int, List, Schema, Str
# declaring schema classes
class Nested_Schema(Schema):
int_attr = Int(default=10)
int_attr_choices = Int(choices=[1, 2, 3], default=1, help="This can be 1,2 or 3")
class Example_Schema(Schema):
int_attr = Int(default=123)
str_attr = Str(default="test")
str_attr_null = Str(default=None)
list_attr_w_default = List(item=Int(), default=[1, 2, 3])
nested = Nested_Schema()
class Simple_Example_Schema(Schema):
str_attr = Str(default="test")
# config without kwargs
cfg = Config(Example_Schema())
print(cfg.data)
# config with data and meta kwrags
cfg_kwargs = Config(
Simple_Example_Schema(),
data={"int_attr": 42, "list_attr": [1, 2, 3]},
meta={"meta_attr": "meta data"},
)
print(cfg_kwargs.data)
print(cfg_kwargs.meta)
# copy the data of a schema
cfg_copy = cfg.copy()
print(cfg_copy)
# get nested schema value
nested_value = cfg.get_nested("nested")
print(nested_value)
nested_value = cfg.get_nested("nonexistentnested")
print(nested_value)