|
7 | 7 | T = TypeVar("T")
|
8 | 8 |
|
9 | 9 |
|
10 |
| -def to_dict(data: Any, name: str = "") -> Any: |
| 10 | +def to_dict(data: dict, name: str = "") -> dict: |
11 | 11 | """Properly format query string for webservice request
|
| 12 | + The passed object itself must be a dict, but the returned value will be |
| 13 | + flattened to a dict with keys like `name[key]` or `name[index][key]`. |
12 | 14 |
|
13 | 15 | Args:
|
14 |
| - data (Any): Query to be formated |
| 16 | + data (dict): Query to be formated |
15 | 17 | name (str, optional): The key of the data. Defaults to "".
|
16 | 18 |
|
17 | 19 | Returns:
|
18 |
| - Any: Formated data |
| 20 | + dict: Formated data |
19 | 21 | """
|
20 |
| - if not data: |
21 |
| - return data |
22 |
| - if isinstance(data, list): |
23 |
| - out = {} |
24 |
| - for idx, val in enumerate(data): |
25 |
| - val = to_dict(val) |
26 |
| - if isinstance(val, dict): |
27 |
| - for key, value in val.items(): |
28 |
| - out[f"{name}[{idx}][{key}]"] = val[key] |
29 |
| - else: |
30 |
| - out_key = name |
31 |
| - # Check if data required name prefix |
32 |
| - if hasattr(data, "name"): |
33 |
| - out_key += f"[{getattr(data, 'name')}]" |
34 |
| - out_key += f"[{idx}]" |
35 |
| - out[out_key] = val |
36 |
| - return out |
37 |
| - if isinstance(data, dict): |
38 |
| - out = {} |
39 |
| - for key, value in data.items(): |
40 |
| - if isinstance(value, list): |
41 |
| - out.update(to_dict(value, key)) |
42 |
| - else: |
43 |
| - out[key] = value |
44 |
| - return out |
45 |
| - if has(data): |
46 |
| - return asdict_attr(data) |
47 |
| - if isinstance(data, datetime): |
48 |
| - return datetime.timestamp(data) |
49 |
| - return data |
| 22 | + |
| 23 | + result = {} |
| 24 | + def inner(prefix: str, data: Any) -> dict: |
| 25 | + pairs = None |
| 26 | + if isinstance(data, list): |
| 27 | + pairs = enumerate(data) |
| 28 | + elif isinstance(data, dict): |
| 29 | + pairs = data.items() |
| 30 | + elif has(data): |
| 31 | + pairs = asdict_attr(data).items() |
| 32 | + |
| 33 | + if pairs is not None: |
| 34 | + for key, value in pairs: |
| 35 | + inner(f"{prefix}[{key}]", value) |
| 36 | + else: |
| 37 | + if isinstance(data, datetime): |
| 38 | + data = datetime.timestamp(data) |
| 39 | + result[prefix] = data |
| 40 | + |
| 41 | + for key, value in data.items(): |
| 42 | + inner(key, value) |
| 43 | + |
| 44 | + return result |
50 | 45 |
|
51 | 46 |
|
52 | 47 | def fromtimestamp(d: str):
|
|
0 commit comments