thordata-sdk 0.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- thordata/__init__.py +137 -0
- thordata/_utils.py +144 -0
- thordata/async_client.py +815 -0
- thordata/client.py +1040 -0
- thordata/demo.py +140 -0
- thordata/enums.py +315 -0
- thordata/exceptions.py +344 -0
- thordata/models.py +840 -0
- thordata/parameters.py +53 -0
- thordata/retry.py +380 -0
- thordata_sdk-0.6.0.dist-info/METADATA +1053 -0
- thordata_sdk-0.6.0.dist-info/RECORD +15 -0
- thordata_sdk-0.6.0.dist-info/WHEEL +5 -0
- thordata_sdk-0.6.0.dist-info/licenses/LICENSE +21 -0
- thordata_sdk-0.6.0.dist-info/top_level.txt +1 -0
thordata/client.py
ADDED
|
@@ -0,0 +1,1040 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Synchronous client for the Thordata API.
|
|
3
|
+
|
|
4
|
+
This module provides the main ThordataClient class for interacting with
|
|
5
|
+
Thordata's proxy network, SERP API, Universal Scraping API, and Web Scraper API.
|
|
6
|
+
|
|
7
|
+
Example:
|
|
8
|
+
>>> from thordata import ThordataClient
|
|
9
|
+
>>>
|
|
10
|
+
>>> client = ThordataClient(
|
|
11
|
+
... scraper_token="your_token",
|
|
12
|
+
... public_token="your_public_token",
|
|
13
|
+
... public_key="your_public_key"
|
|
14
|
+
... )
|
|
15
|
+
>>>
|
|
16
|
+
>>> # Use the proxy network
|
|
17
|
+
>>> response = client.get("https://httpbin.org/ip")
|
|
18
|
+
>>> print(response.json())
|
|
19
|
+
>>>
|
|
20
|
+
>>> # Search with SERP API
|
|
21
|
+
>>> results = client.serp_search("python tutorial", engine="google")
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import logging
|
|
27
|
+
import os
|
|
28
|
+
from typing import Any, Dict, List, Optional, Union
|
|
29
|
+
|
|
30
|
+
import requests
|
|
31
|
+
|
|
32
|
+
from . import __version__ as _sdk_version
|
|
33
|
+
from ._utils import (
|
|
34
|
+
build_auth_headers,
|
|
35
|
+
build_public_api_headers,
|
|
36
|
+
build_user_agent,
|
|
37
|
+
decode_base64_image,
|
|
38
|
+
extract_error_message,
|
|
39
|
+
parse_json_response,
|
|
40
|
+
)
|
|
41
|
+
from .enums import Engine, ProxyType
|
|
42
|
+
from .exceptions import (
|
|
43
|
+
ThordataConfigError,
|
|
44
|
+
ThordataNetworkError,
|
|
45
|
+
ThordataTimeoutError,
|
|
46
|
+
raise_for_code,
|
|
47
|
+
)
|
|
48
|
+
from .models import (
|
|
49
|
+
ProxyConfig,
|
|
50
|
+
ProxyProduct,
|
|
51
|
+
ScraperTaskConfig,
|
|
52
|
+
SerpRequest,
|
|
53
|
+
UniversalScrapeRequest,
|
|
54
|
+
)
|
|
55
|
+
from .retry import RetryConfig, with_retry
|
|
56
|
+
|
|
57
|
+
logger = logging.getLogger(__name__)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class ThordataClient:
|
|
61
|
+
"""
|
|
62
|
+
The official synchronous Python client for Thordata.
|
|
63
|
+
|
|
64
|
+
This client handles authentication and communication with:
|
|
65
|
+
- Proxy Network (Residential/Datacenter/Mobile/ISP via HTTP/HTTPS)
|
|
66
|
+
- SERP API (Real-time Search Engine Results)
|
|
67
|
+
- Universal Scraping API (Web Unlocker - Single Page Rendering)
|
|
68
|
+
- Web Scraper API (Async Task Management)
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
scraper_token: The API token from your Dashboard.
|
|
72
|
+
public_token: The public API token (for task status, locations).
|
|
73
|
+
public_key: The public API key.
|
|
74
|
+
proxy_host: Custom proxy gateway host (optional).
|
|
75
|
+
proxy_port: Custom proxy gateway port (optional).
|
|
76
|
+
timeout: Default request timeout in seconds (default: 30).
|
|
77
|
+
retry_config: Configuration for automatic retries (optional).
|
|
78
|
+
|
|
79
|
+
Example:
|
|
80
|
+
>>> client = ThordataClient(
|
|
81
|
+
... scraper_token="your_scraper_token",
|
|
82
|
+
... public_token="your_public_token",
|
|
83
|
+
... public_key="your_public_key"
|
|
84
|
+
... )
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
# API Endpoints
|
|
88
|
+
BASE_URL = "https://scraperapi.thordata.com"
|
|
89
|
+
UNIVERSAL_URL = "https://universalapi.thordata.com"
|
|
90
|
+
API_URL = "https://api.thordata.com/api/web-scraper-api"
|
|
91
|
+
LOCATIONS_URL = "https://api.thordata.com/api/locations"
|
|
92
|
+
|
|
93
|
+
def __init__(
|
|
94
|
+
self,
|
|
95
|
+
scraper_token: str,
|
|
96
|
+
public_token: Optional[str] = None,
|
|
97
|
+
public_key: Optional[str] = None,
|
|
98
|
+
proxy_host: str = "pr.thordata.net",
|
|
99
|
+
proxy_port: int = 9999,
|
|
100
|
+
timeout: int = 30,
|
|
101
|
+
retry_config: Optional[RetryConfig] = None,
|
|
102
|
+
scraperapi_base_url: Optional[str] = None,
|
|
103
|
+
universalapi_base_url: Optional[str] = None,
|
|
104
|
+
web_scraper_api_base_url: Optional[str] = None,
|
|
105
|
+
locations_base_url: Optional[str] = None,
|
|
106
|
+
) -> None:
|
|
107
|
+
"""Initialize the Thordata Client."""
|
|
108
|
+
if not scraper_token:
|
|
109
|
+
raise ThordataConfigError("scraper_token is required")
|
|
110
|
+
|
|
111
|
+
self.scraper_token = scraper_token
|
|
112
|
+
self.public_token = public_token
|
|
113
|
+
self.public_key = public_key
|
|
114
|
+
|
|
115
|
+
# Proxy configuration
|
|
116
|
+
self._proxy_host = proxy_host
|
|
117
|
+
self._proxy_port = proxy_port
|
|
118
|
+
self._default_timeout = timeout
|
|
119
|
+
|
|
120
|
+
# Retry configuration
|
|
121
|
+
self._retry_config = retry_config or RetryConfig()
|
|
122
|
+
|
|
123
|
+
# Build default proxy URL (for basic usage)
|
|
124
|
+
self._default_proxy_url = (
|
|
125
|
+
f"http://td-customer-{self.scraper_token}:@{proxy_host}:{proxy_port}"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
# Sessions:
|
|
129
|
+
# - _proxy_session: used for proxy network traffic to target sites
|
|
130
|
+
# - _api_session: used for Thordata APIs (SERP/Universal/Tasks/Locations)
|
|
131
|
+
#
|
|
132
|
+
# We intentionally do NOT set session-level proxies for _api_session,
|
|
133
|
+
# so developers can rely on system proxy settings (e.g., Clash) via env vars.
|
|
134
|
+
self._proxy_session = requests.Session()
|
|
135
|
+
self._proxy_session.trust_env = False
|
|
136
|
+
self._proxy_session.proxies = {
|
|
137
|
+
"http": self._default_proxy_url,
|
|
138
|
+
"https": self._default_proxy_url,
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
self._api_session = requests.Session()
|
|
142
|
+
self._api_session.trust_env = True
|
|
143
|
+
|
|
144
|
+
self._api_session.headers.update(
|
|
145
|
+
{"User-Agent": build_user_agent(_sdk_version, "requests")}
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
# Base URLs (allow override via args or env vars for testing and custom routing)
|
|
149
|
+
scraperapi_base = (
|
|
150
|
+
scraperapi_base_url
|
|
151
|
+
or os.getenv("THORDATA_SCRAPERAPI_BASE_URL")
|
|
152
|
+
or self.BASE_URL
|
|
153
|
+
).rstrip("/")
|
|
154
|
+
|
|
155
|
+
universalapi_base = (
|
|
156
|
+
universalapi_base_url
|
|
157
|
+
or os.getenv("THORDATA_UNIVERSALAPI_BASE_URL")
|
|
158
|
+
or self.UNIVERSAL_URL
|
|
159
|
+
).rstrip("/")
|
|
160
|
+
|
|
161
|
+
web_scraper_api_base = (
|
|
162
|
+
web_scraper_api_base_url
|
|
163
|
+
or os.getenv("THORDATA_WEB_SCRAPER_API_BASE_URL")
|
|
164
|
+
or self.API_URL
|
|
165
|
+
).rstrip("/")
|
|
166
|
+
|
|
167
|
+
locations_base = (
|
|
168
|
+
locations_base_url
|
|
169
|
+
or os.getenv("THORDATA_LOCATIONS_BASE_URL")
|
|
170
|
+
or self.LOCATIONS_URL
|
|
171
|
+
).rstrip("/")
|
|
172
|
+
|
|
173
|
+
self._serp_url = f"{scraperapi_base}/request"
|
|
174
|
+
self._builder_url = f"{scraperapi_base}/builder"
|
|
175
|
+
self._universal_url = f"{universalapi_base}/request"
|
|
176
|
+
self._status_url = f"{web_scraper_api_base}/tasks-status"
|
|
177
|
+
self._download_url = f"{web_scraper_api_base}/tasks-download"
|
|
178
|
+
self._locations_base_url = locations_base
|
|
179
|
+
|
|
180
|
+
# =========================================================================
|
|
181
|
+
# Proxy Network Methods
|
|
182
|
+
# =========================================================================
|
|
183
|
+
|
|
184
|
+
def get(
|
|
185
|
+
self,
|
|
186
|
+
url: str,
|
|
187
|
+
*,
|
|
188
|
+
proxy_config: Optional[ProxyConfig] = None,
|
|
189
|
+
timeout: Optional[int] = None,
|
|
190
|
+
**kwargs: Any,
|
|
191
|
+
) -> requests.Response:
|
|
192
|
+
"""
|
|
193
|
+
Send a GET request through the Thordata Proxy Network.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
url: The target URL.
|
|
197
|
+
proxy_config: Custom proxy configuration for geo-targeting/sessions.
|
|
198
|
+
timeout: Request timeout in seconds.
|
|
199
|
+
**kwargs: Additional arguments to pass to requests.get().
|
|
200
|
+
|
|
201
|
+
Returns:
|
|
202
|
+
The response object.
|
|
203
|
+
|
|
204
|
+
Example:
|
|
205
|
+
>>> # Basic request
|
|
206
|
+
>>> response = client.get("https://httpbin.org/ip")
|
|
207
|
+
>>>
|
|
208
|
+
>>> # With geo-targeting
|
|
209
|
+
>>> from thordata.models import ProxyConfig
|
|
210
|
+
>>> config = ProxyConfig(
|
|
211
|
+
... username="myuser",
|
|
212
|
+
... password="mypass",
|
|
213
|
+
... country="us",
|
|
214
|
+
... city="seattle"
|
|
215
|
+
... )
|
|
216
|
+
>>> response = client.get("https://httpbin.org/ip", proxy_config=config)
|
|
217
|
+
"""
|
|
218
|
+
logger.debug(f"Proxy GET request: {url}")
|
|
219
|
+
|
|
220
|
+
timeout = timeout or self._default_timeout
|
|
221
|
+
|
|
222
|
+
if proxy_config:
|
|
223
|
+
proxies = proxy_config.to_proxies_dict()
|
|
224
|
+
kwargs["proxies"] = proxies
|
|
225
|
+
|
|
226
|
+
return self._request_with_retry("GET", url, timeout=timeout, **kwargs)
|
|
227
|
+
|
|
228
|
+
def post(
|
|
229
|
+
self,
|
|
230
|
+
url: str,
|
|
231
|
+
*,
|
|
232
|
+
proxy_config: Optional[ProxyConfig] = None,
|
|
233
|
+
timeout: Optional[int] = None,
|
|
234
|
+
**kwargs: Any,
|
|
235
|
+
) -> requests.Response:
|
|
236
|
+
"""
|
|
237
|
+
Send a POST request through the Thordata Proxy Network.
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
url: The target URL.
|
|
241
|
+
proxy_config: Custom proxy configuration.
|
|
242
|
+
timeout: Request timeout in seconds.
|
|
243
|
+
**kwargs: Additional arguments to pass to requests.post().
|
|
244
|
+
|
|
245
|
+
Returns:
|
|
246
|
+
The response object.
|
|
247
|
+
"""
|
|
248
|
+
logger.debug(f"Proxy POST request: {url}")
|
|
249
|
+
|
|
250
|
+
timeout = timeout or self._default_timeout
|
|
251
|
+
|
|
252
|
+
if proxy_config:
|
|
253
|
+
proxies = proxy_config.to_proxies_dict()
|
|
254
|
+
kwargs["proxies"] = proxies
|
|
255
|
+
|
|
256
|
+
return self._request_with_retry("POST", url, timeout=timeout, **kwargs)
|
|
257
|
+
|
|
258
|
+
def build_proxy_url(
|
|
259
|
+
self,
|
|
260
|
+
*,
|
|
261
|
+
country: Optional[str] = None,
|
|
262
|
+
state: Optional[str] = None,
|
|
263
|
+
city: Optional[str] = None,
|
|
264
|
+
session_id: Optional[str] = None,
|
|
265
|
+
session_duration: Optional[int] = None,
|
|
266
|
+
product: Union[ProxyProduct, str] = ProxyProduct.RESIDENTIAL,
|
|
267
|
+
) -> str:
|
|
268
|
+
"""
|
|
269
|
+
Build a proxy URL with custom targeting options.
|
|
270
|
+
|
|
271
|
+
This is a convenience method for creating proxy URLs without
|
|
272
|
+
manually constructing a ProxyConfig.
|
|
273
|
+
|
|
274
|
+
Args:
|
|
275
|
+
country: Target country code (e.g., 'us', 'gb').
|
|
276
|
+
state: Target state (e.g., 'california').
|
|
277
|
+
city: Target city (e.g., 'seattle').
|
|
278
|
+
session_id: Session ID for sticky sessions.
|
|
279
|
+
session_duration: Session duration in minutes (1-90).
|
|
280
|
+
product: Proxy product type.
|
|
281
|
+
|
|
282
|
+
Returns:
|
|
283
|
+
The proxy URL string.
|
|
284
|
+
|
|
285
|
+
Example:
|
|
286
|
+
>>> url = client.build_proxy_url(country="us", city="seattle")
|
|
287
|
+
>>> proxies = {"http": url, "https": url}
|
|
288
|
+
>>> requests.get("https://example.com", proxies=proxies)
|
|
289
|
+
"""
|
|
290
|
+
config = ProxyConfig(
|
|
291
|
+
username=self.scraper_token,
|
|
292
|
+
password="",
|
|
293
|
+
host=self._proxy_host,
|
|
294
|
+
port=self._proxy_port,
|
|
295
|
+
product=product,
|
|
296
|
+
country=country,
|
|
297
|
+
state=state,
|
|
298
|
+
city=city,
|
|
299
|
+
session_id=session_id,
|
|
300
|
+
session_duration=session_duration,
|
|
301
|
+
)
|
|
302
|
+
return config.build_proxy_url()
|
|
303
|
+
|
|
304
|
+
# =========================================================================
|
|
305
|
+
# SERP API Methods
|
|
306
|
+
# =========================================================================
|
|
307
|
+
|
|
308
|
+
def serp_search(
|
|
309
|
+
self,
|
|
310
|
+
query: str,
|
|
311
|
+
*,
|
|
312
|
+
engine: Union[Engine, str] = Engine.GOOGLE,
|
|
313
|
+
num: int = 10,
|
|
314
|
+
country: Optional[str] = None,
|
|
315
|
+
language: Optional[str] = None,
|
|
316
|
+
search_type: Optional[str] = None,
|
|
317
|
+
device: Optional[str] = None,
|
|
318
|
+
render_js: Optional[bool] = None,
|
|
319
|
+
no_cache: Optional[bool] = None,
|
|
320
|
+
output_format: str = "json",
|
|
321
|
+
**kwargs: Any,
|
|
322
|
+
) -> Dict[str, Any]:
|
|
323
|
+
"""
|
|
324
|
+
Execute a real-time SERP (Search Engine Results Page) search.
|
|
325
|
+
|
|
326
|
+
Args:
|
|
327
|
+
query: The search keywords.
|
|
328
|
+
engine: Search engine (google, bing, yandex, duckduckgo, baidu).
|
|
329
|
+
num: Number of results to retrieve (default: 10).
|
|
330
|
+
country: Country code for localized results (e.g., 'us').
|
|
331
|
+
language: Language code for interface (e.g., 'en').
|
|
332
|
+
search_type: Type of search (images, news, shopping, videos, etc.).
|
|
333
|
+
device: Device type ('desktop', 'mobile', 'tablet').
|
|
334
|
+
render_js: Enable JavaScript rendering in SERP (render_js=True).
|
|
335
|
+
no_cache: Disable internal caching (no_cache=True).
|
|
336
|
+
output_format: 'json' to return parsed JSON (default),
|
|
337
|
+
'html' to return HTML wrapped in {'html': ...}.
|
|
338
|
+
**kwargs: Additional engine-specific parameters.
|
|
339
|
+
|
|
340
|
+
Returns:
|
|
341
|
+
Dict[str, Any]: Parsed JSON results or a dict with 'html' key.
|
|
342
|
+
|
|
343
|
+
Example:
|
|
344
|
+
>>> # Basic search
|
|
345
|
+
>>> results = client.serp_search("python tutorial")
|
|
346
|
+
>>>
|
|
347
|
+
>>> # With options
|
|
348
|
+
>>> results = client.serp_search(
|
|
349
|
+
... "laptop reviews",
|
|
350
|
+
... engine="google",
|
|
351
|
+
... num=20,
|
|
352
|
+
... country="us",
|
|
353
|
+
... search_type="shopping",
|
|
354
|
+
... device="mobile",
|
|
355
|
+
... render_js=True,
|
|
356
|
+
... no_cache=True,
|
|
357
|
+
... )
|
|
358
|
+
"""
|
|
359
|
+
# Normalize engine
|
|
360
|
+
engine_str = engine.value if isinstance(engine, Engine) else engine.lower()
|
|
361
|
+
|
|
362
|
+
# Build request using model
|
|
363
|
+
request = SerpRequest(
|
|
364
|
+
query=query,
|
|
365
|
+
engine=engine_str,
|
|
366
|
+
num=num,
|
|
367
|
+
country=country,
|
|
368
|
+
language=language,
|
|
369
|
+
search_type=search_type,
|
|
370
|
+
device=device,
|
|
371
|
+
render_js=render_js,
|
|
372
|
+
no_cache=no_cache,
|
|
373
|
+
output_format=output_format,
|
|
374
|
+
extra_params=kwargs,
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
payload = request.to_payload()
|
|
378
|
+
headers = build_auth_headers(self.scraper_token)
|
|
379
|
+
|
|
380
|
+
logger.info(f"SERP Search: {engine_str} - {query}")
|
|
381
|
+
|
|
382
|
+
try:
|
|
383
|
+
response = self._api_session.post(
|
|
384
|
+
self._serp_url,
|
|
385
|
+
data=payload,
|
|
386
|
+
headers=headers,
|
|
387
|
+
timeout=60,
|
|
388
|
+
)
|
|
389
|
+
response.raise_for_status()
|
|
390
|
+
|
|
391
|
+
# JSON mode (default)
|
|
392
|
+
if output_format.lower() == "json":
|
|
393
|
+
data = response.json()
|
|
394
|
+
|
|
395
|
+
if isinstance(data, dict):
|
|
396
|
+
code = data.get("code")
|
|
397
|
+
if code is not None and code != 200:
|
|
398
|
+
msg = extract_error_message(data)
|
|
399
|
+
raise_for_code(
|
|
400
|
+
f"SERP API Error: {msg}",
|
|
401
|
+
code=code,
|
|
402
|
+
payload=data,
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
return parse_json_response(data)
|
|
406
|
+
|
|
407
|
+
# HTML mode: wrap as dict to keep return type stable
|
|
408
|
+
return {"html": response.text}
|
|
409
|
+
|
|
410
|
+
except requests.Timeout as e:
|
|
411
|
+
raise ThordataTimeoutError(
|
|
412
|
+
f"SERP request timed out: {e}",
|
|
413
|
+
original_error=e,
|
|
414
|
+
) from e
|
|
415
|
+
except requests.RequestException as e:
|
|
416
|
+
raise ThordataNetworkError(
|
|
417
|
+
f"SERP request failed: {e}",
|
|
418
|
+
original_error=e,
|
|
419
|
+
) from e
|
|
420
|
+
|
|
421
|
+
def serp_search_advanced(self, request: SerpRequest) -> Dict[str, Any]:
|
|
422
|
+
"""
|
|
423
|
+
Execute a SERP search using a SerpRequest object.
|
|
424
|
+
|
|
425
|
+
This method provides full control over all search parameters.
|
|
426
|
+
|
|
427
|
+
Args:
|
|
428
|
+
request: A SerpRequest object with all parameters configured.
|
|
429
|
+
|
|
430
|
+
Returns:
|
|
431
|
+
Dict[str, Any]: Parsed JSON results or dict with 'html' key.
|
|
432
|
+
|
|
433
|
+
Example:
|
|
434
|
+
>>> from thordata.models import SerpRequest
|
|
435
|
+
>>> request = SerpRequest(
|
|
436
|
+
... query="python programming",
|
|
437
|
+
... engine="google",
|
|
438
|
+
... num=50,
|
|
439
|
+
... country="us",
|
|
440
|
+
... language="en",
|
|
441
|
+
... search_type="news",
|
|
442
|
+
... time_filter="week",
|
|
443
|
+
... safe_search=True
|
|
444
|
+
... )
|
|
445
|
+
>>> results = client.serp_search_advanced(request)
|
|
446
|
+
"""
|
|
447
|
+
payload = request.to_payload()
|
|
448
|
+
headers = build_auth_headers(self.scraper_token)
|
|
449
|
+
|
|
450
|
+
logger.info(f"SERP Advanced Search: {request.engine} - {request.query}")
|
|
451
|
+
|
|
452
|
+
try:
|
|
453
|
+
response = self._api_session.post(
|
|
454
|
+
self._serp_url,
|
|
455
|
+
data=payload,
|
|
456
|
+
headers=headers,
|
|
457
|
+
timeout=60,
|
|
458
|
+
)
|
|
459
|
+
response.raise_for_status()
|
|
460
|
+
|
|
461
|
+
if request.output_format.lower() == "json":
|
|
462
|
+
data = response.json()
|
|
463
|
+
|
|
464
|
+
if isinstance(data, dict):
|
|
465
|
+
code = data.get("code")
|
|
466
|
+
if code is not None and code != 200:
|
|
467
|
+
msg = extract_error_message(data)
|
|
468
|
+
raise_for_code(
|
|
469
|
+
f"SERP API Error: {msg}",
|
|
470
|
+
code=code,
|
|
471
|
+
payload=data,
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
return parse_json_response(data)
|
|
475
|
+
|
|
476
|
+
return {"html": response.text}
|
|
477
|
+
|
|
478
|
+
except requests.Timeout as e:
|
|
479
|
+
raise ThordataTimeoutError(
|
|
480
|
+
f"SERP request timed out: {e}",
|
|
481
|
+
original_error=e,
|
|
482
|
+
) from e
|
|
483
|
+
except requests.RequestException as e:
|
|
484
|
+
raise ThordataNetworkError(
|
|
485
|
+
f"SERP request failed: {e}",
|
|
486
|
+
original_error=e,
|
|
487
|
+
) from e
|
|
488
|
+
|
|
489
|
+
# =========================================================================
|
|
490
|
+
# Universal Scraping API (Web Unlocker) Methods
|
|
491
|
+
# =========================================================================
|
|
492
|
+
|
|
493
|
+
def universal_scrape(
|
|
494
|
+
self,
|
|
495
|
+
url: str,
|
|
496
|
+
*,
|
|
497
|
+
js_render: bool = False,
|
|
498
|
+
output_format: str = "html",
|
|
499
|
+
country: Optional[str] = None,
|
|
500
|
+
block_resources: Optional[str] = None,
|
|
501
|
+
wait: Optional[int] = None,
|
|
502
|
+
wait_for: Optional[str] = None,
|
|
503
|
+
**kwargs: Any,
|
|
504
|
+
) -> Union[str, bytes]:
|
|
505
|
+
"""
|
|
506
|
+
Scrape a URL using the Universal Scraping API (Web Unlocker).
|
|
507
|
+
|
|
508
|
+
Automatically bypasses Cloudflare, CAPTCHAs, and antibot systems.
|
|
509
|
+
|
|
510
|
+
Args:
|
|
511
|
+
url: Target URL.
|
|
512
|
+
js_render: Enable JavaScript rendering (headless browser).
|
|
513
|
+
output_format: "html" or "png" (screenshot).
|
|
514
|
+
country: Geo-targeting country code.
|
|
515
|
+
block_resources: Resources to block (e.g., 'script,image').
|
|
516
|
+
wait: Wait time in milliseconds after page load.
|
|
517
|
+
wait_for: CSS selector to wait for.
|
|
518
|
+
**kwargs: Additional parameters.
|
|
519
|
+
|
|
520
|
+
Returns:
|
|
521
|
+
HTML string or PNG bytes depending on output_format.
|
|
522
|
+
|
|
523
|
+
Example:
|
|
524
|
+
>>> # Get HTML
|
|
525
|
+
>>> html = client.universal_scrape("https://example.com", js_render=True)
|
|
526
|
+
>>>
|
|
527
|
+
>>> # Get screenshot
|
|
528
|
+
>>> png = client.universal_scrape(
|
|
529
|
+
... "https://example.com",
|
|
530
|
+
... js_render=True,
|
|
531
|
+
... output_format="png"
|
|
532
|
+
... )
|
|
533
|
+
>>> with open("screenshot.png", "wb") as f:
|
|
534
|
+
... f.write(png)
|
|
535
|
+
"""
|
|
536
|
+
request = UniversalScrapeRequest(
|
|
537
|
+
url=url,
|
|
538
|
+
js_render=js_render,
|
|
539
|
+
output_format=output_format,
|
|
540
|
+
country=country,
|
|
541
|
+
block_resources=block_resources,
|
|
542
|
+
wait=wait,
|
|
543
|
+
wait_for=wait_for,
|
|
544
|
+
extra_params=kwargs,
|
|
545
|
+
)
|
|
546
|
+
|
|
547
|
+
return self.universal_scrape_advanced(request)
|
|
548
|
+
|
|
549
|
+
def universal_scrape_advanced(
|
|
550
|
+
self, request: UniversalScrapeRequest
|
|
551
|
+
) -> Union[str, bytes]:
|
|
552
|
+
"""
|
|
553
|
+
Scrape using a UniversalScrapeRequest object for full control.
|
|
554
|
+
|
|
555
|
+
Args:
|
|
556
|
+
request: A UniversalScrapeRequest with all parameters.
|
|
557
|
+
|
|
558
|
+
Returns:
|
|
559
|
+
HTML string or PNG bytes.
|
|
560
|
+
"""
|
|
561
|
+
payload = request.to_payload()
|
|
562
|
+
headers = build_auth_headers(self.scraper_token)
|
|
563
|
+
|
|
564
|
+
logger.info(
|
|
565
|
+
f"Universal Scrape: {request.url} (format: {request.output_format})"
|
|
566
|
+
)
|
|
567
|
+
|
|
568
|
+
try:
|
|
569
|
+
response = self._api_session.post(
|
|
570
|
+
self._universal_url,
|
|
571
|
+
data=payload,
|
|
572
|
+
headers=headers,
|
|
573
|
+
timeout=60,
|
|
574
|
+
)
|
|
575
|
+
response.raise_for_status()
|
|
576
|
+
|
|
577
|
+
return self._process_universal_response(response, request.output_format)
|
|
578
|
+
|
|
579
|
+
except requests.Timeout as e:
|
|
580
|
+
raise ThordataTimeoutError(
|
|
581
|
+
f"Universal scrape timed out: {e}", original_error=e
|
|
582
|
+
) from e
|
|
583
|
+
except requests.RequestException as e:
|
|
584
|
+
raise ThordataNetworkError(
|
|
585
|
+
f"Universal scrape failed: {e}", original_error=e
|
|
586
|
+
) from e
|
|
587
|
+
|
|
588
|
+
def _process_universal_response(
|
|
589
|
+
self, response: requests.Response, output_format: str
|
|
590
|
+
) -> Union[str, bytes]:
|
|
591
|
+
"""Process the response from Universal API."""
|
|
592
|
+
# Try to parse as JSON
|
|
593
|
+
try:
|
|
594
|
+
resp_json = response.json()
|
|
595
|
+
except ValueError:
|
|
596
|
+
# Raw content returned
|
|
597
|
+
if output_format.lower() == "png":
|
|
598
|
+
return response.content
|
|
599
|
+
return response.text
|
|
600
|
+
|
|
601
|
+
# Check for API-level errors
|
|
602
|
+
if isinstance(resp_json, dict):
|
|
603
|
+
code = resp_json.get("code")
|
|
604
|
+
if code is not None and code != 200:
|
|
605
|
+
msg = extract_error_message(resp_json)
|
|
606
|
+
raise_for_code(
|
|
607
|
+
f"Universal API Error: {msg}", code=code, payload=resp_json
|
|
608
|
+
)
|
|
609
|
+
|
|
610
|
+
# Extract HTML
|
|
611
|
+
if "html" in resp_json:
|
|
612
|
+
return resp_json["html"]
|
|
613
|
+
|
|
614
|
+
# Extract PNG
|
|
615
|
+
if "png" in resp_json:
|
|
616
|
+
return decode_base64_image(resp_json["png"])
|
|
617
|
+
|
|
618
|
+
# Fallback
|
|
619
|
+
return str(resp_json)
|
|
620
|
+
|
|
621
|
+
# =========================================================================
|
|
622
|
+
# Web Scraper API (Task-based) Methods
|
|
623
|
+
# =========================================================================
|
|
624
|
+
|
|
625
|
+
def create_scraper_task(
|
|
626
|
+
self,
|
|
627
|
+
file_name: str,
|
|
628
|
+
spider_id: str,
|
|
629
|
+
spider_name: str,
|
|
630
|
+
parameters: Dict[str, Any],
|
|
631
|
+
universal_params: Optional[Dict[str, Any]] = None,
|
|
632
|
+
) -> str:
|
|
633
|
+
"""
|
|
634
|
+
Create an asynchronous Web Scraper task.
|
|
635
|
+
|
|
636
|
+
Note: Get spider_id and spider_name from the Thordata Dashboard.
|
|
637
|
+
|
|
638
|
+
Args:
|
|
639
|
+
file_name: Name for the output file.
|
|
640
|
+
spider_id: Spider identifier from Dashboard.
|
|
641
|
+
spider_name: Spider name (e.g., "youtube.com").
|
|
642
|
+
parameters: Spider-specific parameters.
|
|
643
|
+
universal_params: Global spider settings.
|
|
644
|
+
|
|
645
|
+
Returns:
|
|
646
|
+
The created task_id.
|
|
647
|
+
|
|
648
|
+
Example:
|
|
649
|
+
>>> task_id = client.create_scraper_task(
|
|
650
|
+
... file_name="youtube_data",
|
|
651
|
+
... spider_id="youtube_video-post_by-url",
|
|
652
|
+
... spider_name="youtube.com",
|
|
653
|
+
... parameters={"url": "https://youtube.com/@channel/videos"}
|
|
654
|
+
... )
|
|
655
|
+
"""
|
|
656
|
+
config = ScraperTaskConfig(
|
|
657
|
+
file_name=file_name,
|
|
658
|
+
spider_id=spider_id,
|
|
659
|
+
spider_name=spider_name,
|
|
660
|
+
parameters=parameters,
|
|
661
|
+
universal_params=universal_params,
|
|
662
|
+
)
|
|
663
|
+
|
|
664
|
+
return self.create_scraper_task_advanced(config)
|
|
665
|
+
|
|
666
|
+
def create_scraper_task_advanced(self, config: ScraperTaskConfig) -> str:
|
|
667
|
+
"""
|
|
668
|
+
Create a scraper task using a ScraperTaskConfig object.
|
|
669
|
+
|
|
670
|
+
Args:
|
|
671
|
+
config: Task configuration.
|
|
672
|
+
|
|
673
|
+
Returns:
|
|
674
|
+
The created task_id.
|
|
675
|
+
"""
|
|
676
|
+
payload = config.to_payload()
|
|
677
|
+
headers = build_auth_headers(self.scraper_token)
|
|
678
|
+
|
|
679
|
+
logger.info(f"Creating Scraper Task: {config.spider_name}")
|
|
680
|
+
|
|
681
|
+
try:
|
|
682
|
+
response = self._api_session.post(
|
|
683
|
+
self._builder_url,
|
|
684
|
+
data=payload,
|
|
685
|
+
headers=headers,
|
|
686
|
+
timeout=30,
|
|
687
|
+
)
|
|
688
|
+
response.raise_for_status()
|
|
689
|
+
|
|
690
|
+
data = response.json()
|
|
691
|
+
code = data.get("code")
|
|
692
|
+
|
|
693
|
+
if code != 200:
|
|
694
|
+
msg = extract_error_message(data)
|
|
695
|
+
raise_for_code(f"Task creation failed: {msg}", code=code, payload=data)
|
|
696
|
+
|
|
697
|
+
return data["data"]["task_id"]
|
|
698
|
+
|
|
699
|
+
except requests.RequestException as e:
|
|
700
|
+
raise ThordataNetworkError(
|
|
701
|
+
f"Task creation failed: {e}", original_error=e
|
|
702
|
+
) from e
|
|
703
|
+
|
|
704
|
+
def get_task_status(self, task_id: str) -> str:
|
|
705
|
+
"""
|
|
706
|
+
Check the status of an asynchronous scraping task.
|
|
707
|
+
|
|
708
|
+
Returns:
|
|
709
|
+
Status string (e.g., "running", "ready", "failed").
|
|
710
|
+
|
|
711
|
+
Raises:
|
|
712
|
+
ThordataConfigError: If public credentials are missing.
|
|
713
|
+
ThordataAPIError: If API returns a non-200 code in JSON payload.
|
|
714
|
+
ThordataNetworkError: If network/HTTP request fails.
|
|
715
|
+
"""
|
|
716
|
+
self._require_public_credentials()
|
|
717
|
+
|
|
718
|
+
headers = build_public_api_headers(
|
|
719
|
+
self.public_token or "", self.public_key or ""
|
|
720
|
+
)
|
|
721
|
+
payload = {"tasks_ids": task_id}
|
|
722
|
+
|
|
723
|
+
try:
|
|
724
|
+
response = self._api_session.post(
|
|
725
|
+
self._status_url,
|
|
726
|
+
data=payload,
|
|
727
|
+
headers=headers,
|
|
728
|
+
timeout=30,
|
|
729
|
+
)
|
|
730
|
+
response.raise_for_status()
|
|
731
|
+
data = response.json()
|
|
732
|
+
|
|
733
|
+
if isinstance(data, dict):
|
|
734
|
+
code = data.get("code")
|
|
735
|
+
if code is not None and code != 200:
|
|
736
|
+
msg = extract_error_message(data)
|
|
737
|
+
raise_for_code(
|
|
738
|
+
f"Task status API Error: {msg}",
|
|
739
|
+
code=code,
|
|
740
|
+
payload=data,
|
|
741
|
+
)
|
|
742
|
+
|
|
743
|
+
items = data.get("data") or []
|
|
744
|
+
for item in items:
|
|
745
|
+
if str(item.get("task_id")) == str(task_id):
|
|
746
|
+
return item.get("status", "unknown")
|
|
747
|
+
|
|
748
|
+
return "unknown"
|
|
749
|
+
|
|
750
|
+
# Unexpected payload type
|
|
751
|
+
raise ThordataNetworkError(
|
|
752
|
+
f"Unexpected task status response type: {type(data).__name__}",
|
|
753
|
+
original_error=None,
|
|
754
|
+
)
|
|
755
|
+
|
|
756
|
+
except requests.Timeout as e:
|
|
757
|
+
raise ThordataTimeoutError(
|
|
758
|
+
f"Status check timed out: {e}", original_error=e
|
|
759
|
+
) from e
|
|
760
|
+
except requests.RequestException as e:
|
|
761
|
+
raise ThordataNetworkError(
|
|
762
|
+
f"Status check failed: {e}", original_error=e
|
|
763
|
+
) from e
|
|
764
|
+
|
|
765
|
+
def safe_get_task_status(self, task_id: str) -> str:
|
|
766
|
+
"""
|
|
767
|
+
Backward-compatible status check.
|
|
768
|
+
|
|
769
|
+
Returns:
|
|
770
|
+
Status string, or "error" on any exception.
|
|
771
|
+
"""
|
|
772
|
+
try:
|
|
773
|
+
return self.get_task_status(task_id)
|
|
774
|
+
except Exception:
|
|
775
|
+
return "error"
|
|
776
|
+
|
|
777
|
+
def get_task_result(self, task_id: str, file_type: str = "json") -> str:
|
|
778
|
+
"""
|
|
779
|
+
Get the download URL for a completed task.
|
|
780
|
+
"""
|
|
781
|
+
self._require_public_credentials()
|
|
782
|
+
|
|
783
|
+
headers = build_public_api_headers(
|
|
784
|
+
self.public_token or "", self.public_key or ""
|
|
785
|
+
)
|
|
786
|
+
payload = {"tasks_id": task_id, "type": file_type}
|
|
787
|
+
|
|
788
|
+
logger.info(f"Getting result URL for Task: {task_id}")
|
|
789
|
+
|
|
790
|
+
try:
|
|
791
|
+
response = self._api_session.post(
|
|
792
|
+
self._download_url,
|
|
793
|
+
data=payload,
|
|
794
|
+
headers=headers,
|
|
795
|
+
timeout=30,
|
|
796
|
+
)
|
|
797
|
+
response.raise_for_status()
|
|
798
|
+
|
|
799
|
+
data = response.json()
|
|
800
|
+
code = data.get("code")
|
|
801
|
+
|
|
802
|
+
if code == 200 and data.get("data"):
|
|
803
|
+
return data["data"]["download"]
|
|
804
|
+
|
|
805
|
+
msg = extract_error_message(data)
|
|
806
|
+
raise_for_code(f"Get result failed: {msg}", code=code, payload=data)
|
|
807
|
+
# This line won't be reached, but satisfies mypy
|
|
808
|
+
raise RuntimeError("Unexpected state")
|
|
809
|
+
|
|
810
|
+
except requests.RequestException as e:
|
|
811
|
+
raise ThordataNetworkError(
|
|
812
|
+
f"Get result failed: {e}", original_error=e
|
|
813
|
+
) from e
|
|
814
|
+
|
|
815
|
+
def wait_for_task(
|
|
816
|
+
self,
|
|
817
|
+
task_id: str,
|
|
818
|
+
*,
|
|
819
|
+
poll_interval: float = 5.0,
|
|
820
|
+
max_wait: float = 600.0,
|
|
821
|
+
) -> str:
|
|
822
|
+
"""
|
|
823
|
+
Wait for a task to complete.
|
|
824
|
+
|
|
825
|
+
Args:
|
|
826
|
+
task_id: The task ID to wait for.
|
|
827
|
+
poll_interval: Seconds between status checks.
|
|
828
|
+
max_wait: Maximum seconds to wait.
|
|
829
|
+
|
|
830
|
+
Returns:
|
|
831
|
+
Final task status.
|
|
832
|
+
|
|
833
|
+
Raises:
|
|
834
|
+
TimeoutError: If max_wait is exceeded.
|
|
835
|
+
|
|
836
|
+
Example:
|
|
837
|
+
>>> task_id = client.create_scraper_task(...)
|
|
838
|
+
>>> status = client.wait_for_task(task_id, max_wait=300)
|
|
839
|
+
>>> if status in ("ready", "success"):
|
|
840
|
+
... url = client.get_task_result(task_id)
|
|
841
|
+
"""
|
|
842
|
+
import time
|
|
843
|
+
|
|
844
|
+
start = time.monotonic()
|
|
845
|
+
|
|
846
|
+
while (time.monotonic() - start) < max_wait:
|
|
847
|
+
status = self.get_task_status(task_id)
|
|
848
|
+
|
|
849
|
+
logger.debug(f"Task {task_id} status: {status}")
|
|
850
|
+
|
|
851
|
+
terminal_statuses = {
|
|
852
|
+
"ready",
|
|
853
|
+
"success",
|
|
854
|
+
"finished",
|
|
855
|
+
"failed",
|
|
856
|
+
"error",
|
|
857
|
+
"cancelled",
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
if status.lower() in terminal_statuses:
|
|
861
|
+
return status
|
|
862
|
+
|
|
863
|
+
time.sleep(poll_interval)
|
|
864
|
+
|
|
865
|
+
raise TimeoutError(f"Task {task_id} did not complete within {max_wait} seconds")
|
|
866
|
+
|
|
867
|
+
# =========================================================================
|
|
868
|
+
# Location API Methods
|
|
869
|
+
# =========================================================================
|
|
870
|
+
|
|
871
|
+
def list_countries(
|
|
872
|
+
self, proxy_type: Union[ProxyType, int] = ProxyType.RESIDENTIAL
|
|
873
|
+
) -> List[Dict[str, Any]]:
|
|
874
|
+
"""
|
|
875
|
+
List supported countries for proxies.
|
|
876
|
+
|
|
877
|
+
Args:
|
|
878
|
+
proxy_type: 1 for residential, 2 for unlimited.
|
|
879
|
+
|
|
880
|
+
Returns:
|
|
881
|
+
List of country records with 'country_code' and 'country_name'.
|
|
882
|
+
"""
|
|
883
|
+
return self._get_locations(
|
|
884
|
+
"countries",
|
|
885
|
+
proxy_type=(
|
|
886
|
+
int(proxy_type) if isinstance(proxy_type, ProxyType) else proxy_type
|
|
887
|
+
),
|
|
888
|
+
)
|
|
889
|
+
|
|
890
|
+
def list_states(
|
|
891
|
+
self,
|
|
892
|
+
country_code: str,
|
|
893
|
+
proxy_type: Union[ProxyType, int] = ProxyType.RESIDENTIAL,
|
|
894
|
+
) -> List[Dict[str, Any]]:
|
|
895
|
+
"""
|
|
896
|
+
List supported states for a country.
|
|
897
|
+
|
|
898
|
+
Args:
|
|
899
|
+
country_code: Country code (e.g., 'US').
|
|
900
|
+
proxy_type: Proxy type.
|
|
901
|
+
|
|
902
|
+
Returns:
|
|
903
|
+
List of state records.
|
|
904
|
+
"""
|
|
905
|
+
return self._get_locations(
|
|
906
|
+
"states",
|
|
907
|
+
proxy_type=(
|
|
908
|
+
int(proxy_type) if isinstance(proxy_type, ProxyType) else proxy_type
|
|
909
|
+
),
|
|
910
|
+
country_code=country_code,
|
|
911
|
+
)
|
|
912
|
+
|
|
913
|
+
def list_cities(
|
|
914
|
+
self,
|
|
915
|
+
country_code: str,
|
|
916
|
+
state_code: Optional[str] = None,
|
|
917
|
+
proxy_type: Union[ProxyType, int] = ProxyType.RESIDENTIAL,
|
|
918
|
+
) -> List[Dict[str, Any]]:
|
|
919
|
+
"""
|
|
920
|
+
List supported cities for a country/state.
|
|
921
|
+
|
|
922
|
+
Args:
|
|
923
|
+
country_code: Country code.
|
|
924
|
+
state_code: Optional state code.
|
|
925
|
+
proxy_type: Proxy type.
|
|
926
|
+
|
|
927
|
+
Returns:
|
|
928
|
+
List of city records.
|
|
929
|
+
"""
|
|
930
|
+
kwargs = {
|
|
931
|
+
"proxy_type": (
|
|
932
|
+
int(proxy_type) if isinstance(proxy_type, ProxyType) else proxy_type
|
|
933
|
+
),
|
|
934
|
+
"country_code": country_code,
|
|
935
|
+
}
|
|
936
|
+
if state_code:
|
|
937
|
+
kwargs["state_code"] = state_code
|
|
938
|
+
|
|
939
|
+
return self._get_locations("cities", **kwargs)
|
|
940
|
+
|
|
941
|
+
def list_asn(
|
|
942
|
+
self,
|
|
943
|
+
country_code: str,
|
|
944
|
+
proxy_type: Union[ProxyType, int] = ProxyType.RESIDENTIAL,
|
|
945
|
+
) -> List[Dict[str, Any]]:
|
|
946
|
+
"""
|
|
947
|
+
List supported ASNs for a country.
|
|
948
|
+
|
|
949
|
+
Args:
|
|
950
|
+
country_code: Country code.
|
|
951
|
+
proxy_type: Proxy type.
|
|
952
|
+
|
|
953
|
+
Returns:
|
|
954
|
+
List of ASN records.
|
|
955
|
+
"""
|
|
956
|
+
return self._get_locations(
|
|
957
|
+
"asn",
|
|
958
|
+
proxy_type=(
|
|
959
|
+
int(proxy_type) if isinstance(proxy_type, ProxyType) else proxy_type
|
|
960
|
+
),
|
|
961
|
+
country_code=country_code,
|
|
962
|
+
)
|
|
963
|
+
|
|
964
|
+
def _get_locations(self, endpoint: str, **kwargs: Any) -> List[Dict[str, Any]]:
|
|
965
|
+
"""Internal method to call locations API."""
|
|
966
|
+
self._require_public_credentials()
|
|
967
|
+
|
|
968
|
+
params = {
|
|
969
|
+
"token": self.public_token,
|
|
970
|
+
"key": self.public_key,
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
for key, value in kwargs.items():
|
|
974
|
+
params[key] = str(value)
|
|
975
|
+
|
|
976
|
+
url = f"{self._locations_base_url}/{endpoint}"
|
|
977
|
+
|
|
978
|
+
logger.debug(f"Locations API request: {url}")
|
|
979
|
+
|
|
980
|
+
# Use requests.get directly (no proxy needed for this API)
|
|
981
|
+
response = self._api_session.get(url, params=params, timeout=30)
|
|
982
|
+
response.raise_for_status()
|
|
983
|
+
|
|
984
|
+
data = response.json()
|
|
985
|
+
|
|
986
|
+
if isinstance(data, dict):
|
|
987
|
+
code = data.get("code")
|
|
988
|
+
if code is not None and code != 200:
|
|
989
|
+
msg = data.get("msg", "")
|
|
990
|
+
raise RuntimeError(
|
|
991
|
+
f"Locations API error ({endpoint}): code={code}, msg={msg}"
|
|
992
|
+
)
|
|
993
|
+
return data.get("data") or []
|
|
994
|
+
|
|
995
|
+
if isinstance(data, list):
|
|
996
|
+
return data
|
|
997
|
+
|
|
998
|
+
return []
|
|
999
|
+
|
|
1000
|
+
# =========================================================================
|
|
1001
|
+
# Helper Methods
|
|
1002
|
+
# =========================================================================
|
|
1003
|
+
|
|
1004
|
+
def _require_public_credentials(self) -> None:
|
|
1005
|
+
"""Ensure public API credentials are available."""
|
|
1006
|
+
if not self.public_token or not self.public_key:
|
|
1007
|
+
raise ThordataConfigError(
|
|
1008
|
+
"public_token and public_key are required for this operation. "
|
|
1009
|
+
"Please provide them when initializing ThordataClient."
|
|
1010
|
+
)
|
|
1011
|
+
|
|
1012
|
+
def _request_with_retry(
|
|
1013
|
+
self, method: str, url: str, **kwargs: Any
|
|
1014
|
+
) -> requests.Response:
|
|
1015
|
+
"""Make a request with automatic retry."""
|
|
1016
|
+
kwargs.setdefault("timeout", self._default_timeout)
|
|
1017
|
+
|
|
1018
|
+
@with_retry(self._retry_config)
|
|
1019
|
+
def _do_request() -> requests.Response:
|
|
1020
|
+
return self._proxy_session.request(method, url, **kwargs)
|
|
1021
|
+
|
|
1022
|
+
try:
|
|
1023
|
+
return _do_request()
|
|
1024
|
+
except requests.Timeout as e:
|
|
1025
|
+
raise ThordataTimeoutError(
|
|
1026
|
+
f"Request timed out: {e}", original_error=e
|
|
1027
|
+
) from e
|
|
1028
|
+
except requests.RequestException as e:
|
|
1029
|
+
raise ThordataNetworkError(f"Request failed: {e}", original_error=e) from e
|
|
1030
|
+
|
|
1031
|
+
def close(self) -> None:
|
|
1032
|
+
"""Close the underlying session."""
|
|
1033
|
+
self._proxy_session.close()
|
|
1034
|
+
self._api_session.close()
|
|
1035
|
+
|
|
1036
|
+
def __enter__(self) -> ThordataClient:
|
|
1037
|
+
return self
|
|
1038
|
+
|
|
1039
|
+
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
1040
|
+
self.close()
|