-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathclient.py
More file actions
384 lines (343 loc) · 12.9 KB
/
client.py
File metadata and controls
384 lines (343 loc) · 12.9 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import base64
import typing
from collections.abc import AsyncIterator, Iterator
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.request_options import RequestOptions
from ..types.proxy_response import ProxyResponse
from .raw_client import AsyncRawProxyClient, RawProxyClient
# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)
_SyncResult = typing.Union[ProxyResponse, typing.Iterator[bytes], None]
_AsyncResult = typing.Union[ProxyResponse, typing.AsyncIterator[bytes], None]
def _add_params_to_url(url: str, params: typing.Dict[str, typing.Any]) -> str:
parsed = urlparse(url)
existing_params = parse_qs(parsed.query)
for key, value in params.items():
existing_params[key] = value if isinstance(value, list) else [value]
new_query = urlencode(existing_params, doseq=True)
return urlunparse(parsed._replace(query=new_query))
def _prepare_request(
url: str,
*,
headers: typing.Optional[typing.Dict[str, typing.Any]],
params: typing.Optional[typing.Dict[str, typing.Any]],
) -> typing.Tuple[str, RequestOptions]:
if params:
url = _add_params_to_url(url, params)
url_64 = base64.urlsafe_b64encode(url.encode()).decode()
downstream_headers = {
f"x-pd-proxy-{name}": value for name, value in (headers or {}).items()
}
return url_64, RequestOptions(additional_headers=downstream_headers)
def _consume_sync(ctx: typing.ContextManager) -> _SyncResult:
"""
Open the raw proxy context, peek at the response payload, and either
return the parsed ProxyResponse (fully-buffered JSON) or a generator that
streams the binary body and closes the underlying response when exhausted.
"""
raw = ctx.__enter__()
data = raw.data
if not isinstance(data, Iterator):
ctx.__exit__(None, None, None)
return data
def _stream() -> typing.Iterator[bytes]:
try:
yield from data
finally:
ctx.__exit__(None, None, None)
return _stream()
async def _consume_async(ctx: typing.AsyncContextManager) -> _AsyncResult:
"""
Async counterpart of `_consume_sync` — returns either a parsed
ProxyResponse or an async generator that streams the binary body.
"""
raw = await ctx.__aenter__()
data = raw.data
if not isinstance(data, AsyncIterator):
await ctx.__aexit__(None, None, None)
return data
async def _stream() -> typing.AsyncIterator[bytes]:
try:
async for chunk in data:
yield chunk
finally:
await ctx.__aexit__(None, None, None)
return _stream()
class ProxyClient:
def __init__(self, *, client_wrapper: SyncClientWrapper):
self._raw_client = RawProxyClient(client_wrapper=client_wrapper)
@property
def with_raw_response(self) -> RawProxyClient:
"""
Retrieves a raw implementation of this client that returns raw responses.
Returns
-------
RawProxyClient
"""
return self._raw_client
def get(
self,
url: str,
*,
external_user_id: str,
account_id: str,
headers: typing.Optional[typing.Dict[str, typing.Any]] = None,
params: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> _SyncResult:
"""
Forward an authenticated GET request to an external API using an external user's account credentials.
Parameters
----------
url : str
Target URL
external_user_id : str
The external user ID for the proxy request
account_id : str
The account ID to use for authentication
headers : typing.Optional[typing.Dict[str, typing.Any]]
Additional headers to include in the request
params : typing.Optional[typing.Dict[str, typing.Any]]
Query parameters to include in the request
Returns
-------
typing.Union[ProxyResponse, typing.Iterator[bytes], None]
ProxyResponse for JSON content, Iterator[bytes] for binary content, None for empty bodies.
Examples
--------
from pipedream import Pipedream, PipedreamEnvironment
client = Pipedream(
client_id="<clientId>",
client_secret="<clientSecret>",
environment=PipedreamEnvironment.PROD,
)
client.proxy.get(
url="https://example.com/api/endpoint",
external_user_id="external_user_id",
account_id="account_id",
headers={"Extra-Downstream-Header": "some value"},
params={"limit": 10},
)
"""
url_64, request_options = _prepare_request(url, headers=headers, params=params)
return _consume_sync(
self._raw_client.get(
url_64,
external_user_id=external_user_id,
account_id=account_id,
request_options=request_options,
)
)
def post(
self,
url: str,
*,
external_user_id: str,
account_id: str,
headers: typing.Optional[typing.Dict[str, typing.Any]] = None,
body: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = None,
params: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> _SyncResult:
"""
Forward an authenticated POST request to an external API using an external user's account credentials.
"""
url_64, request_options = _prepare_request(url, headers=headers, params=params)
return _consume_sync(
self._raw_client.post(
url_64,
external_user_id=external_user_id,
account_id=account_id,
request=body or {},
request_options=request_options,
)
)
def put(
self,
url: str,
*,
external_user_id: str,
account_id: str,
headers: typing.Optional[typing.Dict[str, typing.Any]] = None,
body: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = None,
params: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> _SyncResult:
"""
Forward an authenticated PUT request to an external API using an external user's account credentials.
"""
url_64, request_options = _prepare_request(url, headers=headers, params=params)
return _consume_sync(
self._raw_client.put(
url_64,
external_user_id=external_user_id,
account_id=account_id,
request=body or {},
request_options=request_options,
)
)
def patch(
self,
url: str,
*,
external_user_id: str,
account_id: str,
headers: typing.Optional[typing.Dict[str, typing.Any]] = None,
body: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = None,
params: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> _SyncResult:
"""
Forward an authenticated PATCH request to an external API using an external user's account credentials.
"""
url_64, request_options = _prepare_request(url, headers=headers, params=params)
return _consume_sync(
self._raw_client.patch(
url_64,
external_user_id=external_user_id,
account_id=account_id,
request=body or {},
request_options=request_options,
)
)
def delete(
self,
url: str,
*,
external_user_id: str,
account_id: str,
headers: typing.Optional[typing.Dict[str, typing.Any]] = None,
params: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> _SyncResult:
"""
Forward an authenticated DELETE request to an external API using an external user's account credentials.
"""
url_64, request_options = _prepare_request(url, headers=headers, params=params)
return _consume_sync(
self._raw_client.delete(
url_64,
external_user_id=external_user_id,
account_id=account_id,
request_options=request_options,
)
)
class AsyncProxyClient:
def __init__(self, *, client_wrapper: AsyncClientWrapper):
self._raw_client = AsyncRawProxyClient(client_wrapper=client_wrapper)
@property
def with_raw_response(self) -> AsyncRawProxyClient:
"""
Retrieves a raw implementation of this client that returns raw responses.
Returns
-------
AsyncRawProxyClient
"""
return self._raw_client
async def get(
self,
url: str,
*,
external_user_id: str,
account_id: str,
headers: typing.Optional[typing.Dict[str, typing.Any]] = None,
params: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> _AsyncResult:
"""
Forward an authenticated GET request to an external API using an external user's account credentials.
"""
url_64, request_options = _prepare_request(url, headers=headers, params=params)
return await _consume_async(
self._raw_client.get(
url_64,
external_user_id=external_user_id,
account_id=account_id,
request_options=request_options,
)
)
async def post(
self,
url: str,
*,
external_user_id: str,
account_id: str,
headers: typing.Optional[typing.Dict[str, typing.Any]] = None,
body: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = None,
params: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> _AsyncResult:
"""
Forward an authenticated POST request to an external API using an external user's account credentials.
"""
url_64, request_options = _prepare_request(url, headers=headers, params=params)
return await _consume_async(
self._raw_client.post(
url_64,
external_user_id=external_user_id,
account_id=account_id,
request=body or {},
request_options=request_options,
)
)
async def put(
self,
url: str,
*,
external_user_id: str,
account_id: str,
headers: typing.Optional[typing.Dict[str, typing.Any]] = None,
body: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = None,
params: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> _AsyncResult:
"""
Forward an authenticated PUT request to an external API using an external user's account credentials.
"""
url_64, request_options = _prepare_request(url, headers=headers, params=params)
return await _consume_async(
self._raw_client.put(
url_64,
external_user_id=external_user_id,
account_id=account_id,
request=body or {},
request_options=request_options,
)
)
async def patch(
self,
url: str,
*,
external_user_id: str,
account_id: str,
headers: typing.Optional[typing.Dict[str, typing.Any]] = None,
body: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = None,
params: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> _AsyncResult:
"""
Forward an authenticated PATCH request to an external API using an external user's account credentials.
"""
url_64, request_options = _prepare_request(url, headers=headers, params=params)
return await _consume_async(
self._raw_client.patch(
url_64,
external_user_id=external_user_id,
account_id=account_id,
request=body or {},
request_options=request_options,
)
)
async def delete(
self,
url: str,
*,
external_user_id: str,
account_id: str,
headers: typing.Optional[typing.Dict[str, typing.Any]] = None,
params: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> _AsyncResult:
"""
Forward an authenticated DELETE request to an external API using an external user's account credentials.
"""
url_64, request_options = _prepare_request(url, headers=headers, params=params)
return await _consume_async(
self._raw_client.delete(
url_64,
external_user_id=external_user_id,
account_id=account_id,
request_options=request_options,
)
)