-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbase_client.py
More file actions
211 lines (178 loc) · 6.5 KB
/
Copy pathbase_client.py
File metadata and controls
211 lines (178 loc) · 6.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# Generated by ariadne-codegen
import json
from typing import IO, Any, Dict, List, Optional, Tuple, TypeVar, cast
import httpx
from pydantic import BaseModel
from pydantic_core import to_jsonable_python
from .base_model import UNSET, Upload
from .exceptions import (
GraphQLClientGraphQLMultiError,
GraphQLClientHttpError,
GraphQLClientInvalidResponseError,
)
Self = TypeVar("Self", bound="BaseClient")
class BaseClient:
def __init__(
self,
url: str = "",
headers: Optional[Dict[str, str]] = None,
http_client: Optional[httpx.Client] = None,
) -> None:
self.url = url
self.headers = headers
self.http_client = http_client if http_client else httpx.Client(headers=headers)
def __enter__(self: Self) -> Self:
return self
def __exit__(
self,
exc_type: object,
exc_val: object,
exc_tb: object,
) -> None:
self.http_client.close()
def execute(
self,
query: str,
operation_name: Optional[str] = None,
variables: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> httpx.Response:
processed_variables, files, files_map = self._process_variables(variables)
if files and files_map:
return self._execute_multipart(
query=query,
operation_name=operation_name,
variables=processed_variables,
files=files,
files_map=files_map,
**kwargs,
)
return self._execute_json(
query=query,
operation_name=operation_name,
variables=processed_variables,
**kwargs,
)
def get_data(self, response: httpx.Response) -> Dict[str, Any]:
if not response.is_success:
raise GraphQLClientHttpError(
status_code=response.status_code, response=response
)
try:
response_json = response.json()
except ValueError as exc:
raise GraphQLClientInvalidResponseError(response=response) from exc
if (not isinstance(response_json, dict)) or (
"data" not in response_json and "errors" not in response_json
):
raise GraphQLClientInvalidResponseError(response=response)
data = response_json.get("data")
errors = response_json.get("errors")
if errors:
raise GraphQLClientGraphQLMultiError.from_errors_dicts(
errors_dicts=errors, data=data
)
return cast(Dict[str, Any], data)
def _process_variables(
self, variables: Optional[Dict[str, Any]]
) -> Tuple[
Dict[str, Any], Dict[str, Tuple[str, IO[bytes], str]], Dict[str, List[str]]
]:
if not variables:
return {}, {}, {}
serializable_variables = self._convert_dict_to_json_serializable(variables)
return self._get_files_from_variables(serializable_variables)
def _convert_dict_to_json_serializable(
self, dict_: Dict[str, Any]
) -> Dict[str, Any]:
return {
key: self._convert_value(value)
for key, value in dict_.items()
if value is not UNSET
}
def _convert_value(self, value: Any) -> Any:
if isinstance(value, BaseModel):
return value.model_dump(by_alias=True, exclude_unset=True)
if isinstance(value, list):
return [self._convert_value(item) for item in value]
return value
def _get_files_from_variables(
self, variables: Dict[str, Any]
) -> Tuple[
Dict[str, Any], Dict[str, Tuple[str, IO[bytes], str]], Dict[str, List[str]]
]:
files_map: Dict[str, List[str]] = {}
files_list: List[Upload] = []
def separate_files(path: str, obj: Any) -> Any:
if isinstance(obj, list):
nulled_list = []
for index, value in enumerate(obj):
value = separate_files(f"{path}.{index}", value)
nulled_list.append(value)
return nulled_list
if isinstance(obj, dict):
nulled_dict = {}
for key, value in obj.items():
value = separate_files(f"{path}.{key}", value)
nulled_dict[key] = value
return nulled_dict
if isinstance(obj, Upload):
if obj in files_list:
file_index = files_list.index(obj)
files_map[str(file_index)].append(path)
else:
file_index = len(files_list)
files_list.append(obj)
files_map[str(file_index)] = [path]
return None
return obj
nulled_variables = separate_files("variables", variables)
files: Dict[str, Tuple[str, IO[bytes], str]] = {
str(i): (file_.filename, cast(IO[bytes], file_.content), file_.content_type)
for i, file_ in enumerate(files_list)
}
return nulled_variables, files, files_map
def _execute_multipart(
self,
query: str,
operation_name: Optional[str],
variables: Dict[str, Any],
files: Dict[str, Tuple[str, IO[bytes], str]],
files_map: Dict[str, List[str]],
**kwargs: Any,
) -> httpx.Response:
data = {
"operations": json.dumps(
{
"query": query,
"operationName": operation_name,
"variables": variables,
},
default=to_jsonable_python,
),
"map": json.dumps(files_map, default=to_jsonable_python),
}
return self.http_client.post(url=self.url, data=data, files=files, **kwargs)
def _execute_json(
self,
query: str,
operation_name: Optional[str],
variables: Dict[str, Any],
**kwargs: Any,
) -> httpx.Response:
headers: Dict[str, str] = {"Content-Type": "application/json"}
headers.update(kwargs.get("headers", {}))
merged_kwargs: Dict[str, Any] = kwargs.copy()
merged_kwargs["headers"] = headers
return self.http_client.post(
url=self.url,
content=json.dumps(
{
"query": query,
"operationName": operation_name,
"variables": variables,
},
default=to_jsonable_python,
),
**merged_kwargs,
)