diff --git a/librefi/utils.py b/librefi/utils.py index c1234ea..2e1c043 100644 --- a/librefi/utils.py +++ b/librefi/utils.py @@ -1,7 +1,7 @@ # flake8: noqa: E501 import re -from urllib.parse import parse_qs, quote +from urllib.parse import parse_qs, quote as qs_quote def get_user_agent(): @@ -20,11 +20,33 @@ def regex_search_string(regexes, string, default=None): def dump_qs(obj): - qs = "" + old_qs = [] + qs = [] for key in obj: - if isinstance(obj[key], (str, int, float)): - qs += quote(key) + "=" + quote(str(obj[key])) - else: - # TODO: support nested dicts and lists - raise TypeError("unknown types in dump_qs") - return qs + old_qs.append((key, obj[key])) + not_flat = True + while not_flat: + not_flat = False + for old_qs_element in old_qs: + if isinstance(old_qs_element[1], (str, int, float)): + qs.append((old_qs_element[0], old_qs_element[1])) + elif isinstance(old_qs_element[1], (dict)): + for subkey in old_qs_element[1]: + qs.append( + (old_qs_element[0] + "[" + subkey + "]", old_qs_element[1][subkey])) + if isinstance(old_qs_element[1][subkey], (dict, list)): + not_flat = True + elif isinstance(old_qs_element[1], (list)): + for element in old_qs_element[1]: + qs.append( + (old_qs_element[0] + "[]", element)) + if isinstance(element, (dict, list)): + not_flat = True + if not_flat: + old_qs = qs + qs = [] + strng = "" + for el in qs: + strng += qs_quote(str(el[0]), encoding="utf8") + "=" + \ + qs_quote(str(el[1]), encoding="utf8") + "&" + return strng[:-1]