Debian Codegraph @

src/anthropic/_qs.py

raw
1 from __future__ import annotations
2
3 from typing import Any, List, Tuple, Union, Mapping, TypeVar
4 from datetime import date, datetime
5 from urllib.parse import parse_qs, urlencode
6 from typing_extensions import get_args
7
8 from ._types import NotGiven, ArrayFormat, NestedFormat, not_given
9 from ._utils import flatten
10
11 _T = TypeVar("_T")
12
13 PrimitiveData = Union[str, int, float, bool, date, datetime, None]
14 # this should be Data = Union[PrimitiveData, "List[Data]", "Tuple[Data]", "Mapping[str, Data]"]
15 # https://github.com/microsoft/pyright/issues/3555
16 Data = Union[PrimitiveData, List[Any], Tuple[Any], "Mapping[str, Any]"]
17 Params = Mapping[str, Data]
18
19
20 class Querystring:
21 array_format: ArrayFormat
22 nested_format: NestedFormat
23
24 def __init__(
25 self,
26 *,
27 array_format: ArrayFormat = "repeat",
28 nested_format: NestedFormat = "brackets",
29 ) -> None:
30 self.array_format = array_format
31 self.nested_format = nested_format
32
33 def parse(self, query: str) -> Mapping[str, object]:
34 # Note: custom format syntax is not supported yet
35 return parse_qs(query)
36
37 def stringify(
38 self,
39 params: Params,
40 *,
41 array_format: ArrayFormat | NotGiven = not_given,
42 nested_format: NestedFormat | NotGiven = not_given,
43 ) -> str:
44 return urlencode(
45 self.stringify_items(
46 params,
47 array_format=array_format,
48 nested_format=nested_format,
49 )
50 )
51
52 def stringify_items(
53 self,
54 params: Params,
55 *,
56 array_format: ArrayFormat | NotGiven = not_given,
57 nested_format: NestedFormat | NotGiven = not_given,
58 ) -> list[tuple[str, str]]:
59 opts = Options(
60 qs=self,
61 array_format=array_format,
62 nested_format=nested_format,
63 )
64 return flatten([self._stringify_item(key, value, opts) for key, value in params.items()])
65
66 def _stringify_item(
67 self,
68 key: str,
69 value: Data,
70 opts: Options,
71 ) -> list[tuple[str, str]]:
72 if isinstance(value, Mapping):
73 items: list[tuple[str, str]] = []
74 nested_format = opts.nested_format
75 for subkey, subvalue in value.items():
76 items.extend(
77 self._stringify_item(
78 # TODO: error if unknown format
79 f"{key}.{subkey}" if nested_format == "dots" else f"{key}[{subkey}]",
80 subvalue,
81 opts,
82 )
83 )
84 return items
85
86 if isinstance(value, (list, tuple)):
87 array_format = opts.array_format
88 if array_format == "comma":
89 return [
90 (
91 key,
92 ",".join(self._primitive_value_to_str(item) for item in value if item is not None),
93 ),
94 ]
95 elif array_format == "repeat":
96 items = []
97 for item in value:
98 items.extend(self._stringify_item(key, item, opts))
99 return items
100 elif array_format == "indices":
101 items = []
102 for i, item in enumerate(value):
103 items.extend(self._stringify_item(f"{key}[{i}]", item, opts))
104 return items
105 elif array_format == "brackets":
106 items = []
107 key = key + "[]"
108 for item in value:
109 items.extend(self._stringify_item(key, item, opts))
110 return items
111 else:
112 raise NotImplementedError(
113 f"Unknown array_format value: {array_format}, choose from {', '.join(get_args(ArrayFormat))}"
114 )
115
116 serialised = self._primitive_value_to_str(value)
117 if not serialised:
118 return []
119 return [(key, serialised)]
120
121 def _primitive_value_to_str(self, value: PrimitiveData) -> str:
122 # copied from httpx
123 if value is True:
124 return "true"
125 elif value is False:
126 return "false"
127 elif value is None:
128 return ""
129 elif isinstance(value, (datetime, date)):
130 return value.isoformat()
131 return str(value)
132
133
134 _qs = Querystring()
135 parse = _qs.parse
136 stringify = _qs.stringify
137 stringify_items = _qs.stringify_items
138
139
140 class Options:
141 array_format: ArrayFormat
142 nested_format: NestedFormat
143
144 def __init__(
145 self,
146 qs: Querystring = _qs,
147 *,
148 array_format: ArrayFormat | NotGiven = not_given,
149 nested_format: NestedFormat | NotGiven = not_given,
150 ) -> None:
151 self.array_format = qs.array_format if isinstance(array_format, NotGiven) else array_format
152 self.nested_format = qs.nested_format if isinstance(nested_format, NotGiven) else nested_format