Skip to content

Added a utility to merge objectFilters, #1468

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions SoftLayer/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

:license: MIT, see LICENSE for more details.
"""
import collections
import datetime
import re
import time
Expand Down Expand Up @@ -57,6 +58,23 @@ def to_dict(self):
for key, val in self.items()}


def dict_merge(dct1, dct2):
"""Recursively merges dct2 and dct1, ideal for merging objectFilter together.

:param dct1: A dictionary
:param dct2: A dictionary
:return: dct1 + dct2
"""

dct = dct1.copy()
for k, _ in dct2.items():
if (k in dct1 and isinstance(dct1[k], dict) and isinstance(dct2[k], collections.Mapping)):
dct[k] = dict_merge(dct1[k], dct2[k])
else:
dct[k] = dct2[k]
return dct


def query_filter(query):
"""Translate a query-style string to a 'filter'.

Expand Down
9 changes: 9 additions & 0 deletions tests/basic_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,15 @@ def test_timezone(self):
self.assertEqual(datetime.timedelta(0), time.dst())
self.assertEqual(datetime.timedelta(0), time.utcoffset())

def test_dict_merge(self):
filter1 = {"virtualGuests": {"hostname": {"operation": "etst"}}}
filter2 = {"virtualGuests": {"id": {"operation": "orderBy", "options": [{"name": "sort", "value": ["DESC"]}]}}}
result = SoftLayer.utils.dict_merge(filter1, filter2)

self.assertEqual(result['virtualGuests']['id']['operation'], 'orderBy')
self.assertNotIn('id', filter1['virtualGuests'])
self.assertEqual(result['virtualGuests']['hostname']['operation'], 'etst')


class TestNestedDict(testing.TestCase):

Expand Down