serpbit 0.2.0__tar.gz → 0.3.0__tar.gz
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.
- {serpbit-0.2.0/src/serpbit.egg-info → serpbit-0.3.0}/PKG-INFO +3 -2
- {serpbit-0.2.0 → serpbit-0.3.0}/README.md +2 -1
- {serpbit-0.2.0 → serpbit-0.3.0}/pyproject.toml +1 -1
- {serpbit-0.2.0 → serpbit-0.3.0}/src/serpbit/_client.py +41 -7
- {serpbit-0.2.0 → serpbit-0.3.0/src/serpbit.egg-info}/PKG-INFO +3 -2
- {serpbit-0.2.0 → serpbit-0.3.0}/tests/test_client.py +31 -0
- {serpbit-0.2.0 → serpbit-0.3.0}/LICENSE +0 -0
- {serpbit-0.2.0 → serpbit-0.3.0}/setup.cfg +0 -0
- {serpbit-0.2.0 → serpbit-0.3.0}/src/serpbit/__init__.py +0 -0
- {serpbit-0.2.0 → serpbit-0.3.0}/src/serpbit/_errors.py +0 -0
- {serpbit-0.2.0 → serpbit-0.3.0}/src/serpbit/_webhook.py +0 -0
- {serpbit-0.2.0 → serpbit-0.3.0}/src/serpbit/py.typed +0 -0
- {serpbit-0.2.0 → serpbit-0.3.0}/src/serpbit.egg-info/SOURCES.txt +0 -0
- {serpbit-0.2.0 → serpbit-0.3.0}/src/serpbit.egg-info/dependency_links.txt +0 -0
- {serpbit-0.2.0 → serpbit-0.3.0}/src/serpbit.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: serpbit
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Google Search, News, Shopping, Images, Videos, Maps, Autocomplete and AI Mode as data: the Serpbit API client.
|
|
5
5
|
Author-email: Serpbit <support@serpbit.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -44,7 +44,8 @@ print(sb.news("wildfire", sort="date", output="md"))
|
|
|
44
44
|
```
|
|
45
45
|
|
|
46
46
|
Every door of the API has a method: `search`, `news`, `shopping`, `shopping_product`, `images`, `videos`, `maps`,
|
|
47
|
-
`autocomplete`, `ai_mode
|
|
47
|
+
`autocomplete`, `ai_mode`, and `custom_search` (Google's Custom Search JSON API, drop-in). Keyword arguments are the
|
|
48
|
+
door's parameters, as the [docs](https://serpbit.com/docs/)
|
|
48
49
|
name them:
|
|
49
50
|
- `True` is sent as `true`;
|
|
50
51
|
- `None` and `False` are left out;
|
|
@@ -25,7 +25,8 @@ print(sb.news("wildfire", sort="date", output="md"))
|
|
|
25
25
|
```
|
|
26
26
|
|
|
27
27
|
Every door of the API has a method: `search`, `news`, `shopping`, `shopping_product`, `images`, `videos`, `maps`,
|
|
28
|
-
`autocomplete`, `ai_mode
|
|
28
|
+
`autocomplete`, `ai_mode`, and `custom_search` (Google's Custom Search JSON API, drop-in). Keyword arguments are the
|
|
29
|
+
door's parameters, as the [docs](https://serpbit.com/docs/)
|
|
29
30
|
name them:
|
|
30
31
|
- `True` is sent as `true`;
|
|
31
32
|
- `None` and `False` are left out;
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "serpbit"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.3.0"
|
|
8
8
|
description = "Google Search, News, Shopping, Images, Videos, Maps, Autocomplete and AI Mode as data: the Serpbit API client."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "MIT"
|
|
@@ -11,11 +11,11 @@ import urllib.request
|
|
|
11
11
|
import uuid
|
|
12
12
|
from typing import Any, Dict, List, Optional, Union
|
|
13
13
|
|
|
14
|
-
from ._errors import APIConnectionError, SerpbitError, error_for
|
|
14
|
+
from ._errors import APIConnectionError, InsufficientCreditsError, SerpbitError, error_for
|
|
15
15
|
|
|
16
16
|
DEFAULT_BASE_URL = "https://api.serpbit.com"
|
|
17
17
|
DEFAULT_CONNECT_URL = "wss://connect.serpbit.com"
|
|
18
|
-
VERSION = "0.
|
|
18
|
+
VERSION = "0.3.0"
|
|
19
19
|
|
|
20
20
|
# A call is retried on these: the rate limit (after Retry-After), Google giving no page in time, our side failing.
|
|
21
21
|
_RETRY = {429, 500, 502, 503, 504}
|
|
@@ -94,6 +94,12 @@ class Serpbit:
|
|
|
94
94
|
"""Google's AI Mode answer with its sources (/v1/ai-mode)."""
|
|
95
95
|
return self.request("/v1/ai-mode", q=q, **params)
|
|
96
96
|
|
|
97
|
+
def custom_search(self, q: str, **params: Any) -> Answer:
|
|
98
|
+
"""Google's Custom Search JSON API, drop-in (/customsearch/v1): its parameters (num, start, dateRestrict,
|
|
99
|
+
siteSearch, searchType="image"...) and its JSON, items[] and all. Out of credits is InsufficientCreditsError
|
|
100
|
+
(Custom Search's 429 quotaExceeded), not retried."""
|
|
101
|
+
return self.request("/customsearch/v1", q=q, **params)
|
|
102
|
+
|
|
97
103
|
# --- batches ---------------------------------------------------------------------------------------------------
|
|
98
104
|
|
|
99
105
|
def batch(self, requests: List[Dict[str, Any]], *, webhook: Optional[str] = None,
|
|
@@ -219,7 +225,7 @@ class Serpbit:
|
|
|
219
225
|
except urllib.error.HTTPError as e:
|
|
220
226
|
body = e.read()
|
|
221
227
|
retry_after = _float(e.headers.get("Retry-After"))
|
|
222
|
-
if e.code in _RETRY and attempt < retries:
|
|
228
|
+
if e.code in _RETRY and attempt < retries and not _out_of_quota(body):
|
|
223
229
|
time.sleep(_backoff(attempt, retry_after))
|
|
224
230
|
attempt += 1
|
|
225
231
|
continue
|
|
@@ -262,13 +268,41 @@ def _backoff(attempt: int, retry_after: Optional[float]) -> float:
|
|
|
262
268
|
return min(0.5 * 2**attempt, 8.0) * (0.75 + random.random() / 2)
|
|
263
269
|
|
|
264
270
|
|
|
265
|
-
def
|
|
271
|
+
def _json(body: bytes) -> Dict[str, Any]:
|
|
266
272
|
try:
|
|
267
273
|
data = json.loads(body)
|
|
268
274
|
except ValueError:
|
|
269
|
-
|
|
270
|
-
if
|
|
271
|
-
|
|
275
|
+
return {}
|
|
276
|
+
return data if isinstance(data, dict) else {}
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _custom_search_error(data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
280
|
+
"""Custom Search's refusal, {"error": {code, message, errors: [{reason}], status}}, or None."""
|
|
281
|
+
err = data.get("error")
|
|
282
|
+
return err if isinstance(err, dict) else None
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _reason(err: Dict[str, Any]) -> Optional[str]:
|
|
286
|
+
for e in err.get("errors") or []:
|
|
287
|
+
if isinstance(e, dict) and e.get("reason"):
|
|
288
|
+
return str(e["reason"])
|
|
289
|
+
return err.get("status")
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _out_of_quota(body: bytes) -> bool:
|
|
293
|
+
"""Custom Search's out of credits: a 429 that waiting does not help."""
|
|
294
|
+
err = _custom_search_error(_json(body))
|
|
295
|
+
return err is not None and _reason(err) == "quotaExceeded"
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _refusal(status: int, body: bytes, request_id: Optional[str], retry_after: Optional[float]) -> SerpbitError:
|
|
299
|
+
data = _json(body)
|
|
300
|
+
err = _custom_search_error(data)
|
|
301
|
+
if err is not None:
|
|
302
|
+
message, code = err.get("message") or f"the API answered {status}", _reason(err)
|
|
303
|
+
if code == "quotaExceeded":
|
|
304
|
+
return InsufficientCreditsError(message, status=status, code=code, request_id=request_id, body=data)
|
|
305
|
+
return error_for(status, message, code=code, request_id=request_id, body=data, retry_after=retry_after)
|
|
272
306
|
message = data.get("message") or f"the API answered {status}"
|
|
273
307
|
return error_for(status, message, code=data.get("error"), request_id=data.get("request_id") or request_id,
|
|
274
308
|
body=data, retry_after=retry_after)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: serpbit
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Google Search, News, Shopping, Images, Videos, Maps, Autocomplete and AI Mode as data: the Serpbit API client.
|
|
5
5
|
Author-email: Serpbit <support@serpbit.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -44,7 +44,8 @@ print(sb.news("wildfire", sort="date", output="md"))
|
|
|
44
44
|
```
|
|
45
45
|
|
|
46
46
|
Every door of the API has a method: `search`, `news`, `shopping`, `shopping_product`, `images`, `videos`, `maps`,
|
|
47
|
-
`autocomplete`, `ai_mode
|
|
47
|
+
`autocomplete`, `ai_mode`, and `custom_search` (Google's Custom Search JSON API, drop-in). Keyword arguments are the
|
|
48
|
+
door's parameters, as the [docs](https://serpbit.com/docs/)
|
|
48
49
|
name them:
|
|
49
50
|
- `True` is sent as `true`;
|
|
50
51
|
- `None` and `False` are left out;
|
|
@@ -25,6 +25,18 @@ class FakeAPI(BaseHTTPRequestHandler):
|
|
|
25
25
|
"request_id": "r-err"}, headers)
|
|
26
26
|
return
|
|
27
27
|
q = FakeAPI.seen[-1]["query"]
|
|
28
|
+
if u.path == "/customsearch/v1":
|
|
29
|
+
refused = {"bad": (400, "invalid", "cr is not supported", "INVALID_ARGUMENT"),
|
|
30
|
+
"broke": (429, "quotaExceeded", "no credits left", "RESOURCE_EXHAUSTED")}.get(q.get("q"))
|
|
31
|
+
if refused:
|
|
32
|
+
status, reason, message, st = refused
|
|
33
|
+
self.send(status, {"error": {"code": status, "message": message, "status": st,
|
|
34
|
+
"errors": [{"message": message, "domain": "global", "reason": reason}]}},
|
|
35
|
+
{"X-Request-Id": "rcse"})
|
|
36
|
+
return
|
|
37
|
+
self.send(200, {"kind": "customsearch#search", "items": [{"title": "A", "link": "https://example.com/a",
|
|
38
|
+
"snippet": "a"}]}, {"X-Credits": "1"})
|
|
39
|
+
return
|
|
28
40
|
if q.get("q") == "broke":
|
|
29
41
|
self.send(402, {"error": "out_of_credits", "message": "no credits left", "request_id": "r402"})
|
|
30
42
|
return
|
|
@@ -106,6 +118,25 @@ class ClientTest(unittest.TestCase):
|
|
|
106
118
|
self.assertEqual(FakeAPI.seen[-1]["path"], path)
|
|
107
119
|
self.assertEqual(FakeAPI.seen[2]["query"], {"product_id": "123"})
|
|
108
120
|
|
|
121
|
+
def test_custom_search_takes_and_gives_custom_searchs_shape(self):
|
|
122
|
+
a = self.sb.custom_search("espresso", num=5, dateRestrict="m1", siteSearch="example.com")
|
|
123
|
+
self.assertEqual(a["items"][0]["link"], "https://example.com/a")
|
|
124
|
+
r = FakeAPI.seen[-1]
|
|
125
|
+
self.assertEqual(r["path"], "/customsearch/v1")
|
|
126
|
+
self.assertEqual(r["query"], {"q": "espresso", "num": "5", "dateRestrict": "m1", "siteSearch": "example.com"})
|
|
127
|
+
self.assertEqual(r["auth"], "Bearer sb_live_test")
|
|
128
|
+
|
|
129
|
+
def test_custom_searchs_refusals_are_read_in_its_shape(self):
|
|
130
|
+
with self.assertRaises(serpbit.BadRequestError) as e:
|
|
131
|
+
self.sb.custom_search("bad")
|
|
132
|
+
self.assertEqual((e.exception.status, e.exception.code, e.exception.message, e.exception.request_id),
|
|
133
|
+
(400, "invalid", "cr is not supported", "rcse"))
|
|
134
|
+
n = len(FakeAPI.seen)
|
|
135
|
+
with self.assertRaises(serpbit.InsufficientCreditsError) as e:
|
|
136
|
+
self.sb.custom_search("broke")
|
|
137
|
+
self.assertEqual((e.exception.status, e.exception.code, e.exception.message), (429, "quotaExceeded", "no credits left"))
|
|
138
|
+
self.assertEqual(len(FakeAPI.seen), n + 1, "out of credits is not asked again")
|
|
139
|
+
|
|
109
140
|
def test_markdown_comes_as_text(self):
|
|
110
141
|
self.assertEqual(self.sb.search("x", output="md"), "# Google results")
|
|
111
142
|
self.assertEqual(self.sb.last_request_id, "rmd")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|