config2py.tools#
Various tools
Functions
|
Get a dict of |
|
Get the local store of configs. |
|
Make a simple config getter from a "central" config source specification. |
|
A decorator factory that sources config params, based on their names, to a config getter that will be provided when calling the wrapped function. |
Classes
|
A |
- config2py.tools.Configs#
alias of
SecureTextFiles
- class config2py.tools.SecureTextFiles(*args, follow_symlinks=True, on_unsafe_folder='warn', **kwargs)[source]#
Bases:
TextFilesA
dol.TextFiles(one text file per key) whose value files are0o600.Config values are often secrets (API keys); plain
TextFileswrites them with the umask default (commonly world-readable0o644). Still anisinstanceofTextFiles, so it is a drop-in replacement (see i2mint/config2py#33).Like
TextFiles, values are UTF-8 on disk whatever the locale, and a failed write raisesKeyError. Unlike it, the value is encoded before the file is opened, so an unencodable value doesn’t leave an emptied file behind (see i2mint/config2py#35).Like
TextFiles(andopen), a value file that is a symlink is followed, and its target is the file written (and tightened to0o600). That is deliberate: it keeps value files symlinked from elsewhere (a dotfiles repo, say) working, and in config2py’s own configs folder (0o700) only its owner can plant a link (see i2mint/config2py#37). If others can write to a folder you pass in, they can plant a link that redirects your secrets: the store warns about such a folder (on_unsafe_folder), andfollow_symlinks=Falserefuses to write through a link (see i2mint/config2py#45).__setitem__relies on threedolinternals:_id_of_key,store.validate_keyand_data_of_obj.dolis unpinned, sotest_secure_text_files_dol_contractchecks they still exist.
- config2py.tools.extract_exports(exports, *, on_missing='warn')[source]#
Get a dict of
{name: value}pairs from thename="value" pairs of unix export lines (that is, lines of the ``export NAME="VALUE"format- Parameters:
exports – Filepath (
stroros.PathLike) or string contents thereofon_missing (
str) – What to do whenexportslooks like a filepath (a single, non-blank line with noexportin it) that is not an existing file:"warn"(the default) issues aMissingConfigFileWarningand returns{},"raise"raisesFileNotFoundError,"ignore"returns{}(see i2mint/config2py#27).
- Return type:
- Returns:
A dict of extracted
{name: value}pairs
>>> extract_exports('export KEY="secret"\nexport TOKEN="arbitrary"') {'KEY': 'secret', 'TOKEN': 'arbitrary'} >>> extract_exports('export KEY="secret"') # a single line of content works too {'KEY': 'secret'}
A mistyped path is not silently read as empty content:
>>> extract_exports('no/such/path/.env', on_missing='raise') Traceback (most recent call last): ... FileNotFoundError: [Errno 2] No such config file: 'no/such/path/.env'
Use case:#
You have access to environment variables through
os.environ, but if you want to extract exports from only a specific file (env vars are often placed in different linked files), or the exports are defined in a string you hold, then this simple parser can be useful.
- config2py.tools.get_configs_local_store(config_src='/home/runner/.config/config2py/configs', *, configs_name='configs', follow_symlinks=True, on_unsafe_folder='warn', kind='auto')[source]#
Get the local store of configs.
- Parameters:
config_src – A specification of the local config store. By default: If it’s a directory, it’s assumed to be a folder of text files. If it’s a file, it’s assumed to be an ini or cfg file. If it’s a string, it’s assumed to be an app name, from which to create a folder (a
pathlib.Pathis always a path).follow_symlinks (
bool) – Whether the store may write through a symlink at a value (or ini) file’s path.Falserefuses to (see i2mint/config2py#45).on_unsafe_folder (
str) –"warn"(default),"raise"or"ignore"when a folder store’s root (or, for an ini file, its folder; a sticky one like/tmpis fine) is owned by another user or writable by its group or by others (seeSecureTextFiles).kind (
str) – How to readconfig_src:"auto"(default),"path"or"app". In"auto"mode, apathlib.Path, an absolute path, or a string containingos.seporos.altsepis a path, and any other string is an app name, even if a directory of that name exists in the current working directory (so as not to change where existing callers read and write; only an existing.ini/.cfgfile of that name is used as a file).kind="path"makes a bare name such as"configs"mean that directory (or file);kind="app"makes any string an app name. See i2mint/config2py#28.
The default,
DFLT_CONFIG_FOLDER, is config2py’s own configs folder. It is created here, on first use, rather than at import (see i2mint/config2py#26).
- config2py.tools.simple_config_getter(configs_src='/home/runner/.config/config2py/configs', *, first_look_in_env_vars=True, ask_user_if_key_not_found=None, config_store_factory=<function get_configs_local_store>)[source]#
Make a simple config getter from a “central” config source specification.
The purpose of this function is to implement a common pattern of getting configs: One that, by default (but optionally), looks in environment variables first, then in a central config store, created via a simple
configs_srcspecification and then, if the key is not found in this “central” store, optionally (but not by default) asks the user for the value and stores it in the central config store.- Parameters:
configs_src (
str) – A specification of the central config store. By default: If it’s a directory (with at least a slash), it’s assumed to be a folder of text files. If it’s a file, it’s assumed to be an ini or cfg file. If it’s a string, it’s assumed to be an app name, from which to create a folderfirst_look_in_env_vars (
bool) – Whether to look in environment variables firstask_user_if_key_not_found (
bool) – Whether to ask the user if the key is not found (and subsequently store the key in the central config store)config_store_factory (
Callable) – A function that takes a config source specification and returns the central config store
- config2py.tools.source_config_params(*config_params)[source]#
A decorator factory that sources config params, based on their names, to a config getter that will be provided when calling the wrapped function.
- Parameters:
config_params – The names of the config params to source
- Returns:
A decorator that sources the config params to the config getter
>>> @source_config_params('a', 'b') ... def foo(a, b, c): ... return a, b, c >>> config = {'a': 1, 'b': 2, 'c': 3} >>> foo(a='a', b='b', c=3, _config_getter=config.get) (1, 2, 3)
A common use case is when you need to partialize a function with configs but the config source is not defined yet.
>>> from functools import partial >>> bar = partial(foo, a='a')
ais set, but you’ll be able to callbarwith different config sources,>>> bar(b='b', c=3, _config_getter=config.get) (1, 2, 3) >>> other_config = {'a': 11, 'b': 22, 'c': 33} >>> bar(b='b', c=3, _config_getter=other_config.get) (11, 22, 3)
What if the function as kwargs? No problem, the decorator will handle it. Just make sure to use the same names for the kwargs as the config params.
>>> @source_config_params('a', 'b', 'd') ... def foo(a, b, c, **kwargs): ... return a, b, c, kwargs >>> config = {'a': 1, 'b': 2, 'c': 3, 'd': 4} >>> foo(a='a', b='b', c=3, d='d', _config_getter=config.get) (1, 2, 3, {'d': 4})
As you can see,
dis sourced as well.