mirror of
https://github.com/netbox-community/netbox.git
synced 2025-07-22 03:56:53 -06:00
Add all() method to UserConfig
This commit is contained in:
parent
d8494e44e7
commit
7c8c85e435
@ -9,6 +9,8 @@ from django.db.models.signals import post_save
|
||||
from django.dispatch import receiver
|
||||
from django.utils import timezone
|
||||
|
||||
from utilities.utils import flatten_dict
|
||||
|
||||
|
||||
__all__ = (
|
||||
'Token',
|
||||
@ -54,6 +56,12 @@ class UserConfig(models.Model):
|
||||
|
||||
return d
|
||||
|
||||
def all(self):
|
||||
"""
|
||||
Return a dictionary of all defined keys and their values.
|
||||
"""
|
||||
return flatten_dict(self.data)
|
||||
|
||||
def set(self, path, value, commit=False):
|
||||
"""
|
||||
Define or overwrite a configuration parameter. Example:
|
||||
|
@ -45,6 +45,20 @@ class UserConfigTest(TestCase):
|
||||
self.assertIsNone(userconfig.get('b.foo.invalid'))
|
||||
self.assertIsNone(userconfig.get('b.foo.x.invalid'))
|
||||
|
||||
def test_all(self):
|
||||
userconfig = self.userconfig
|
||||
flattened_data = {
|
||||
'a': True,
|
||||
'b.foo': 101,
|
||||
'b.bar': 102,
|
||||
'c.foo.x': 201,
|
||||
'c.bar.y': 202,
|
||||
'c.baz.z': 203,
|
||||
}
|
||||
|
||||
# Retrieve a flattened dictionary containing all config data
|
||||
self.assertEqual(userconfig.all(), flattened_data)
|
||||
|
||||
def test_set(self):
|
||||
userconfig = self.userconfig
|
||||
|
||||
|
@ -239,3 +239,21 @@ def shallow_compare_dict(source_dict, destination_dict, exclude=None):
|
||||
difference[key] = destination_dict[key]
|
||||
|
||||
return difference
|
||||
|
||||
|
||||
def flatten_dict(d, prefix='', separator='.'):
|
||||
"""
|
||||
Flatten netsted dictionaries into a single level by joining key names with a separator.
|
||||
|
||||
:param d: The dictionary to be flattened
|
||||
:param prefix: Initial prefix (if any)
|
||||
:param separator: The character to use when concatenating key names
|
||||
"""
|
||||
ret = {}
|
||||
for k, v in d.items():
|
||||
key = separator.join([prefix, k]) if prefix else k
|
||||
if type(v) is dict:
|
||||
ret.update(flatten_dict(v, prefix=key))
|
||||
else:
|
||||
ret[key] = v
|
||||
return ret
|
||||
|
Loading…
Reference in New Issue
Block a user