Utils¶
- django_docker_helpers.utils._materialize_dict(bundle, separator='.')[source]¶
Traverses and transforms a given dict
bundle
into tuples of(key_path, value)
.- Parameters
bundle (
dict
) – a dict to traverseseparator (
str
) – build paths with a given separator
- Return type
Generator
[Tuple
[str
,Any
],None
,None
]- Returns
a generator of tuples
(materialized_path, value)
Example: >>> list(_materialize_dict({‘test’: {‘path’: 1}, ‘key’: ‘val’}, ‘.’)) >>> [(‘key’, ‘val’), (‘test.path’, 1)]
- django_docker_helpers.utils.coerce_str_to_bool(val, strict=False)[source]¶
Converts a given string
val
into a boolean.- Parameters
val (
Union
[str
,int
,None
]) – any string representation of booleanstrict (
bool
) – raiseValueError
ifval
does not look like a boolean-like object
- Return type
bool
- Returns
True
ifval
is thruthy,False
otherwise.- Raises
ValueError – if
strict
specified andval
got anything except['', 0, 1, true, false, on, off, True, False]
- django_docker_helpers.utils.dot_path(obj, path, default=None, separator='.')[source]¶
Provides an access to elements of a mixed dict/object type by a delimiter-separated path.
class O1: my_dict = {'a': {'b': [1, 2]}} class O2: def __init__(self): self.nested = O1() class O3: final = O2() o = O3() assert utils.dot_path(o, 'final.nested.my_dict.a.b.1') == 2
True
- Parameters
obj (
object
) – object or dictpath (
str
) – path to valuedefault (
Optional
[Any
]) – default value if chain resolve failedseparator (
str
) –.
by default
- Returns
value or default
- django_docker_helpers.utils.dotkey(obj, path, default=None, separator='.')[source]¶
Provides an interface to traverse nested dict values by dot-separated paths. Wrapper for
dpath.util.get
.- Parameters
obj (
dict
) – dict like{'some': {'value': 3}}
path (
str
) –'some.value'
separator –
'.'
or'/'
or whateverdefault – default for KeyError
- Returns
dict value or default value
- django_docker_helpers.utils.env_bool_flag(flag_name, strict=False, env=None)[source]¶
Converts an environment variable into a boolean. Empty string (presence in env) is treated as
True
.- Parameters
flag_name (
str
) – an environment variable namestrict (
bool
) – raiseValueError
if aflag_name
value connot be coerced into a boolean in obvious wayenv (
Optional
[Dict
[str
,str
]]) – a dict with environment variables, default isos.environ
- Return type
bool
- Returns
True
ifflag_name
is thruthy,False
otherwise.- Raises
ValueError – if
strict
specified andval
got anything except['', 0, 1, true, false, True, False]
- django_docker_helpers.utils.env_tristate_flag(flag_name, strict=False, env=None)[source]¶
Converts an environment variable into a boolean or None if not present. Empty string (presence in env) is treated as
True
.- Parameters
flag_name (
str
) – an environment variable namestrict (
bool
) – raiseValueError
if aflag_name
value connot be coerced into a boolean in obvious wayenv (
Optional
[Dict
[str
,str
]]) – a dict with environment variables, default isos.environ
- Return type
Optional
[bool
]- Returns
True
ifflag_name
is thruthy,False
otherwise.- Raises
ValueError – if
strict
specified andval
got anything except['', 0, 1, true, false, True, False]
- django_docker_helpers.utils.is_dockerized(flag_name='DOCKERIZED', strict=False)[source]¶
Reads env
DOCKERIZED
variable as a boolean, or detects docker.- Parameters
flag_name (
str
) – environment variable namestrict (
bool
) – raise aValueError
if variable does not look like a normal boolean
- Return type
bool
- Returns
True
if has truthyDOCKERIZED
env,False
otherwise
- django_docker_helpers.utils.is_production(flag_name='PRODUCTION', strict=False)[source]¶
Reads env
PRODUCTION
variable as a boolean.- Parameters
flag_name (
str
) – environment variable namestrict (
bool
) – raise aValueError
if variable does not look like a normal boolean
- Return type
bool
- Returns
True
if has truthyPRODUCTION
env,False
otherwise
- django_docker_helpers.utils.materialize_dict(bundle, separator='.')[source]¶
Transforms a given
bundle
into a sorted list of tuples with materialized value paths and values:('path.to.value', <value>)
. Output is ordered by depth: the deepest element first.- Parameters
bundle (
dict
) – a dict to materializeseparator (
str
) – build paths with a given separator
- Return type
List
[Tuple
[str
,Any
]]- Returns
a depth descending and alphabetically ascending sorted list (-deep, asc), the longest first
sample = { 'a': 1, 'aa': 1, 'b': { 'c': 1, 'b': 1, 'a': 1, 'aa': 1, 'aaa': { 'a': 1 } } } materialize_dict(sample, '/') [ ('b/aaa/a', 1), ('b/a', 1), ('b/aa', 1), ('b/b', 1), ('b/c', 1), ('a', 1), ('aa', 1) ]
- django_docker_helpers.utils.mp_serialize_dict(bundle, separator='.', serialize=<function dump>, value_prefix='::YAML::\\n')[source]¶
Transforms a given
bundle
into a sorted list of tuples with materialized value paths and values:('path.to.value', b'<some>')
. If the<some>
value is not an instance of a basic type, it’s serialized withserialize
callback. If this value is an empty string, it’s serialized anyway to enforce correct type if storage backend does not support saving empty strings.- Parameters
bundle (
dict
) – a dict to materializeseparator (
str
) – build paths with a given separatorserialize (
Optional
[Callable
]) – a method to serialize non-basic types, default isyaml.dump
value_prefix (
str
) – a prefix for non-basic serialized types
- Return type
List
[Tuple
[str
,bytes
]]- Returns
a list of tuples
(mat_path, b'value')
sample = { 'bool_flag': '', # flag 'unicode': 'вася', 'none_value': None, 'debug': True, 'mixed': ['ascii', 'юникод', 1, {'d': 1}, {'b': 2}], 'nested': { 'a': { 'b': 2, 'c': b'bytes', } } } result = mp_serialize_dict(sample, separator='/') assert result == [ ('nested/a/b', b'2'), ('nested/a/c', b'bytes'), ('bool_flag', b"::YAML::\n''\n"), ('debug', b'true'), ('mixed', b'::YAML::\n- ascii\n- ' b'"\\u044E\\u043D\\u0438\\u043A\\u043E\\u0434"\n- 1\n- ' b'{d: 1}\n- {b: 2}\n'), ('none_value', None), ('unicode', b'\xd0\xb2\xd0\xb0\xd1\x81\xd1\x8f') ]
- django_docker_helpers.utils.run_env_once(f)[source]¶
A decorator to prevent
manage.py
from running code twice for everything. (https://stackoverflow.com/questions/16546652/why-does-django-run-everything-twice)- Parameters
f (
Callable
) – function or method to decorate- Return type
Callable
- Returns
callable
- django_docker_helpers.utils.shred(key_name, value, field_names=('password', 'secret', 'pass', 'pwd', 'key', 'token', 'auth', 'cred'))[source]¶
Replaces sensitive data in
value
with*
ifkey_name
contains something that looks like a secret.- Parameters
field_names (
Iterable
[str
]) – a list of key names that can possibly contain sensitive datakey_name (
str
) – a key name to checkvalue (
Any
) – a value to mask
- Return type
Union
[Any
,str
]- Returns
an unchanged value if nothing to hide,
'*' * len(str(value))
otherwise
- django_docker_helpers.utils.wf(raw_str, flush=True, prevent_completion_polluting=True, stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]¶
Writes a given
raw_str
into astream
. Ignores output ifprevent_completion_polluting
is set and there’s no extrasys.argv
arguments present (a bash completion issue).- Parameters
raw_str (
str
) – a raw string to printflush (
bool
) – executeflush()
prevent_completion_polluting (
bool
) – don’t write anything iflen(sys.argv) <= 1
stream (
TextIO
) –sys.stdout
by default
- Returns
None