Model Recipes¶
Anyconfig Model Recipe¶
This is the easiest way of using cfgtree. Anyconfig abstract the loading of the configuration file, handling a large variety of file format transparently.
Two variant are provided:
AnyConfigModel
: that can read enviroment variables and configuration fileAnyConfigCliModel
: that tries to parse the command line argument
Base Model¶
-
class
cfgtree.
ConfigBaseModel
(model=None, environ_var_prefix=None, storage=None, cmd_line_parser=None, autosave=False)[source]¶ Main configuration class
You need to inherit from this base class and implement the following members:
model
: hierarchical dictionary representing the configuration treeenviron_var_prefix
: prefix for environment variable, to avoid conflictsstorage
: class to use for configuration storagecmd_line_parser
: which command line argument parser to use
Usage:
from cfgtree import ConfigBaseModel from cfgtree.cmdline_parsers.argparse import ArgparseCmdlineParser class MyAppConfig(ConfigBaseModel): # All environment variables should start by MYAPP_ to avoid collision with other # application's or system's environment variables environ_var_prefix = "MYAPP_" # My configuration should be read from a single JSON file storage = JsonConfigFile( # User can overwrite the configuration file name with this environment variable environ_var="MYAPP_COMMON_CONFIG_FILE", # or this command line parameter long_param="--config-file", short_param="-c", # If not set, search for the `config.json` file in the current directory default_filename="config.json", ) # Use `argparse` to parse the command line cmd_line_parser = ArgparseCmdlineParser() # Here is the main settings model for the application model = { # Redefine configfile with ConfigFileCfg so that it appears in --help "configfile": ConfigFileCfg(long_param="--config-file", short_param="-c", summary="Configuration file"), # can holds a version information for the storage file "version": VersionCfg(), "general": { "verbose": BoolCfg(short_param='-v', long_param="--verbose", summary='Enable verbose output logs'), "logfile": StringCfg(short_param="-l", summary='Output log to file'), }, } # As an example, the 'verbose' setting can then be configured by: # - environment variable "MYAPP_GENERAL_VERBOSE" # - command line option ``--verbose` # - key ``general.verbose`` in configuration file ``config.json`` cfg = MyAppConfig() # Read cfg.get_cfg_value("group1.dict_opt.key1") # Write cfg.set_cfg_value("group1.dict_opt.key1", "newval")
-
autosave
= False¶
-
cmd_line_parser
= None¶
-
environ_var_prefix
= None¶
-
model
= None¶
-
storage
= None¶