megalania 0.2.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.
- megalania-0.2.0/LICENSE +21 -0
- megalania-0.2.0/PKG-INFO +74 -0
- megalania-0.2.0/README.md +55 -0
- megalania-0.2.0/megalania/__init__.py +291 -0
- megalania-0.2.0/megalania/__main__.py +5 -0
- megalania-0.2.0/megalania/_generated/__init__.py +8 -0
- megalania-0.2.0/megalania/_generated/api/__init__.py +1 -0
- megalania-0.2.0/megalania/_generated/api/default/__init__.py +1 -0
- megalania-0.2.0/megalania/_generated/api/default/get_domain_stats.py +257 -0
- megalania-0.2.0/megalania/_generated/api/default/get_geos.py +164 -0
- megalania-0.2.0/megalania/_generated/api/default/get_tier.py +258 -0
- megalania-0.2.0/megalania/_generated/api/default/map_site.py +297 -0
- megalania-0.2.0/megalania/_generated/api/default/scrape.py +652 -0
- megalania-0.2.0/megalania/_generated/api/default/scrape_json.py +341 -0
- megalania-0.2.0/megalania/_generated/client.py +280 -0
- megalania-0.2.0/megalania/_generated/errors.py +16 -0
- megalania-0.2.0/megalania/_generated/models/__init__.py +87 -0
- megalania-0.2.0/megalania/_generated/models/domain_stats.py +102 -0
- megalania-0.2.0/megalania/_generated/models/domain_stats_breakdown_item.py +108 -0
- megalania-0.2.0/megalania/_generated/models/error.py +68 -0
- megalania-0.2.0/megalania/_generated/models/error_error.py +90 -0
- megalania-0.2.0/megalania/_generated/models/error_error_code.py +72 -0
- megalania-0.2.0/megalania/_generated/models/geos.py +92 -0
- megalania-0.2.0/megalania/_generated/models/geos_routes_item.py +89 -0
- megalania-0.2.0/megalania/_generated/models/geos_routes_item_engine.py +9 -0
- megalania-0.2.0/megalania/_generated/models/geos_routes_item_proxy_tier.py +10 -0
- megalania-0.2.0/megalania/_generated/models/get_domain_stats_days.py +10 -0
- megalania-0.2.0/megalania/_generated/models/get_tier_country_code.py +256 -0
- megalania-0.2.0/megalania/_generated/models/get_tier_response_types_item.py +16 -0
- megalania-0.2.0/megalania/_generated/models/map_request.py +72 -0
- megalania-0.2.0/megalania/_generated/models/map_result.py +105 -0
- megalania-0.2.0/megalania/_generated/models/map_result_stopped.py +72 -0
- megalania-0.2.0/megalania/_generated/models/map_result_urls_item.py +72 -0
- megalania-0.2.0/megalania/_generated/models/map_result_urls_item_source.py +9 -0
- megalania-0.2.0/megalania/_generated/models/scrape_country_code.py +256 -0
- megalania-0.2.0/megalania/_generated/models/scrape_engine.py +9 -0
- megalania-0.2.0/megalania/_generated/models/scrape_envelope.py +401 -0
- megalania-0.2.0/megalania/_generated/models/scrape_envelope_country_code.py +256 -0
- megalania-0.2.0/megalania/_generated/models/scrape_envelope_engine.py +9 -0
- megalania-0.2.0/megalania/_generated/models/scrape_envelope_extract_model.py +10 -0
- megalania-0.2.0/megalania/_generated/models/scrape_envelope_identity.py +9 -0
- megalania-0.2.0/megalania/_generated/models/scrape_envelope_method.py +9 -0
- megalania-0.2.0/megalania/_generated/models/scrape_envelope_only_main_content.py +9 -0
- megalania-0.2.0/megalania/_generated/models/scrape_envelope_proxy_tier.py +10 -0
- megalania-0.2.0/megalania/_generated/models/scrape_envelope_screenshot.py +9 -0
- megalania-0.2.0/megalania/_generated/models/scrape_extract_model.py +10 -0
- megalania-0.2.0/megalania/_generated/models/scrape_identity.py +9 -0
- megalania-0.2.0/megalania/_generated/models/scrape_network.py +9 -0
- megalania-0.2.0/megalania/_generated/models/scrape_only_main_content.py +9 -0
- megalania-0.2.0/megalania/_generated/models/scrape_proxy_tier.py +10 -0
- megalania-0.2.0/megalania/_generated/models/scrape_response_types_item.py +16 -0
- megalania-0.2.0/megalania/_generated/models/scrape_screenshot.py +9 -0
- megalania-0.2.0/megalania/_generated/models/tier.py +169 -0
- megalania-0.2.0/megalania/_generated/models/tier_capabilities.py +72 -0
- megalania-0.2.0/megalania/_generated/models/tier_capabilities_browser_item.py +10 -0
- megalania-0.2.0/megalania/_generated/models/tier_capabilities_http_item.py +10 -0
- megalania-0.2.0/megalania/_generated/models/tier_pending_type_0.py +80 -0
- megalania-0.2.0/megalania/_generated/models/tier_quotes.py +87 -0
- megalania-0.2.0/megalania/_generated/types.py +54 -0
- megalania-0.2.0/megalania/cli.py +182 -0
- megalania-0.2.0/megalania/skill/SKILL.md +35 -0
- megalania-0.2.0/megalania/skill/reference.md +270 -0
- megalania-0.2.0/megalania.egg-info/PKG-INFO +74 -0
- megalania-0.2.0/megalania.egg-info/SOURCES.txt +68 -0
- megalania-0.2.0/megalania.egg-info/dependency_links.txt +1 -0
- megalania-0.2.0/megalania.egg-info/entry_points.txt +2 -0
- megalania-0.2.0/megalania.egg-info/requires.txt +3 -0
- megalania-0.2.0/megalania.egg-info/top_level.txt +1 -0
- megalania-0.2.0/pyproject.toml +29 -0
- megalania-0.2.0/setup.cfg +4 -0
megalania-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Megalania
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
megalania-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: megalania
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Megalania scraping API client, generated from the OpenAPI document.
|
|
5
|
+
Author: Megalania
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://megalania.io
|
|
8
|
+
Project-URL: Documentation, https://docs.megalania.io/guides/sdk-python
|
|
9
|
+
Project-URL: Source, https://github.com/megalania/megalania-python
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: httpx<0.29,>=0.23
|
|
16
|
+
Requires-Dist: attrs>=22.2
|
|
17
|
+
Requires-Dist: typing-extensions>=4.6
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# Megalania Python SDK
|
|
21
|
+
|
|
22
|
+
**Beta.** A small client for the Megalania scraping API. One call returns a
|
|
23
|
+
page as HTML, Markdown or JSON, and batches, monitors, map and tier have a
|
|
24
|
+
method each. You get the body, the response headers as
|
|
25
|
+
typed fields, and a `MegalaniaError` with the error code and message.
|
|
26
|
+
|
|
27
|
+
- It retries once on a 429, after `Retry-After`, and never on anything else.
|
|
28
|
+
- Every scrape, map and create call sends an `Idempotency-Key`, so a repeat is never charged twice.
|
|
29
|
+
- The types are generated from the Megalania OpenAPI document.
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
Python 3.10 or newer.
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
pip install megalania
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## One page
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
import os
|
|
43
|
+
|
|
44
|
+
from megalania import Megalania, MegalaniaError
|
|
45
|
+
|
|
46
|
+
with Megalania(os.environ["MEG_API_KEY"]) as meg:
|
|
47
|
+
try:
|
|
48
|
+
page = meg.scrape("https://example.com/", response_types="markdown")
|
|
49
|
+
except MegalaniaError as e:
|
|
50
|
+
print(e.status, e.code, e.message, e.request_id)
|
|
51
|
+
raise
|
|
52
|
+
print(page.headers.credits_charged, page.text[:200])
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
The client calls `https://get.megalania.io` unless you pass `base_url`.
|
|
56
|
+
|
|
57
|
+
Batches, monitors, map and tier have their own methods, named after their
|
|
58
|
+
REST operation: `get_tier`, `map_site`, `create_batch`, `get_batch`,
|
|
59
|
+
`list_batch_items`, `cancel_batch`, `create_monitor`, `list_monitors` and
|
|
60
|
+
more. They call `https://api.megalania.io` unless you pass `api_url`:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
with Megalania(os.environ["MEG_API_KEY"]) as meg:
|
|
64
|
+
batch = meg.create_batch(["https://docs.megalania.io/start/quickstart"], response_types="markdown")
|
|
65
|
+
print(meg.get_batch(batch["id"]))
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Docs
|
|
69
|
+
|
|
70
|
+
The full guide is at https://docs.megalania.io/guides/sdk-python.
|
|
71
|
+
|
|
72
|
+
## License
|
|
73
|
+
|
|
74
|
+
MIT. See `LICENSE`. Security reports: see `SECURITY.md`.
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Megalania Python SDK
|
|
2
|
+
|
|
3
|
+
**Beta.** A small client for the Megalania scraping API. One call returns a
|
|
4
|
+
page as HTML, Markdown or JSON, and batches, monitors, map and tier have a
|
|
5
|
+
method each. You get the body, the response headers as
|
|
6
|
+
typed fields, and a `MegalaniaError` with the error code and message.
|
|
7
|
+
|
|
8
|
+
- It retries once on a 429, after `Retry-After`, and never on anything else.
|
|
9
|
+
- Every scrape, map and create call sends an `Idempotency-Key`, so a repeat is never charged twice.
|
|
10
|
+
- The types are generated from the Megalania OpenAPI document.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
Python 3.10 or newer.
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
pip install megalania
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## One page
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import os
|
|
24
|
+
|
|
25
|
+
from megalania import Megalania, MegalaniaError
|
|
26
|
+
|
|
27
|
+
with Megalania(os.environ["MEG_API_KEY"]) as meg:
|
|
28
|
+
try:
|
|
29
|
+
page = meg.scrape("https://example.com/", response_types="markdown")
|
|
30
|
+
except MegalaniaError as e:
|
|
31
|
+
print(e.status, e.code, e.message, e.request_id)
|
|
32
|
+
raise
|
|
33
|
+
print(page.headers.credits_charged, page.text[:200])
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The client calls `https://get.megalania.io` unless you pass `base_url`.
|
|
37
|
+
|
|
38
|
+
Batches, monitors, map and tier have their own methods, named after their
|
|
39
|
+
REST operation: `get_tier`, `map_site`, `create_batch`, `get_batch`,
|
|
40
|
+
`list_batch_items`, `cancel_batch`, `create_monitor`, `list_monitors` and
|
|
41
|
+
more. They call `https://api.megalania.io` unless you pass `api_url`:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
with Megalania(os.environ["MEG_API_KEY"]) as meg:
|
|
45
|
+
batch = meg.create_batch(["https://docs.megalania.io/start/quickstart"], response_types="markdown")
|
|
46
|
+
print(meg.get_batch(batch["id"]))
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Docs
|
|
50
|
+
|
|
51
|
+
The full guide is at https://docs.megalania.io/guides/sdk-python.
|
|
52
|
+
|
|
53
|
+
## License
|
|
54
|
+
|
|
55
|
+
MIT. See `LICENSE`. Security reports: see `SECURITY.md`.
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import dataclasses
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
import typing
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import uuid
|
|
9
|
+
from collections.abc import Iterator
|
|
10
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclasses.dataclass(frozen=True)
|
|
17
|
+
class Headers:
|
|
18
|
+
request_id: str | None = None
|
|
19
|
+
cache_control: str | None = None
|
|
20
|
+
content_security_policy: str | None = None
|
|
21
|
+
content_type_options: str | None = None
|
|
22
|
+
referrer_policy: str | None = None
|
|
23
|
+
credits_charged: int | None = None
|
|
24
|
+
credits_route: int | None = None
|
|
25
|
+
credits_output: int | None = None
|
|
26
|
+
credits_other: int | None = None
|
|
27
|
+
engine: str | None = None
|
|
28
|
+
target_status: int | None = None
|
|
29
|
+
timing_target_ms: int | None = None
|
|
30
|
+
route: str | None = None
|
|
31
|
+
geo: str | None = None
|
|
32
|
+
identity: str | None = None
|
|
33
|
+
billing: str | None = None
|
|
34
|
+
block: str | None = None
|
|
35
|
+
challenge: str | None = None
|
|
36
|
+
vendor: str | None = None
|
|
37
|
+
hint: str | None = None
|
|
38
|
+
untried: str | None = None
|
|
39
|
+
untried_reason: str | None = None
|
|
40
|
+
hops: str | None = None
|
|
41
|
+
ladder_truncated: str | None = None
|
|
42
|
+
truncated: str | None = None
|
|
43
|
+
network_truncated: str | None = None
|
|
44
|
+
compact_truncated: str | None = None
|
|
45
|
+
document: str | None = None
|
|
46
|
+
document_units: int | None = None
|
|
47
|
+
document_truncated: str | None = None
|
|
48
|
+
usage_warning: str | None = None
|
|
49
|
+
cache: str | None = None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def header_name(field: str) -> str:
|
|
53
|
+
words = "-".join(w.capitalize() for w in field.split("_"))
|
|
54
|
+
plain = ("cache_control", "content_security_policy", "referrer_policy")
|
|
55
|
+
return words if field in plain else f"X-{words}"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclasses.dataclass(frozen=True)
|
|
59
|
+
class Result:
|
|
60
|
+
status: int
|
|
61
|
+
content: bytes
|
|
62
|
+
headers: Headers
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def text(self) -> str:
|
|
66
|
+
return self.content.decode("utf-8", errors="replace")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class MegalaniaError(Exception):
|
|
70
|
+
def __init__(self, status: int, code: str | None, message: str, field: str | None,
|
|
71
|
+
request_id: str | None, report_url: str | None, headers: Headers = Headers()):
|
|
72
|
+
super().__init__(message)
|
|
73
|
+
self.headers = headers
|
|
74
|
+
self.status = status
|
|
75
|
+
self.code = code
|
|
76
|
+
self.message = message
|
|
77
|
+
self.field = field
|
|
78
|
+
self.request_id = request_id
|
|
79
|
+
self.report_url = report_url
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Megalania:
|
|
83
|
+
def __init__(self, api_key: str | None = None, base_url: str = "https://get.megalania.io",
|
|
84
|
+
api_url: str = "https://api.megalania.io", timeout: float = 100.0):
|
|
85
|
+
api_key = api_key or os.environ.get("MEG_API_KEY")
|
|
86
|
+
if not api_key:
|
|
87
|
+
raise ValueError("no API key: pass api_key or set MEG_API_KEY")
|
|
88
|
+
self._timeout = timeout
|
|
89
|
+
self.base_url = base_url
|
|
90
|
+
self.api_url = api_url
|
|
91
|
+
auth = {"Authorization": f"Bearer {api_key}"}
|
|
92
|
+
self._http = httpx.Client(base_url=base_url, headers=auth, timeout=httpx.Timeout(timeout))
|
|
93
|
+
self._api = httpx.Client(base_url=api_url, headers=auth, timeout=httpx.Timeout(timeout))
|
|
94
|
+
|
|
95
|
+
def __repr__(self) -> str:
|
|
96
|
+
return f"Megalania(base_url={self.base_url!r}, api_url={self.api_url!r})"
|
|
97
|
+
|
|
98
|
+
def __enter__(self) -> "Megalania":
|
|
99
|
+
return self
|
|
100
|
+
|
|
101
|
+
def __exit__(self, *exc: object) -> None:
|
|
102
|
+
self.close()
|
|
103
|
+
|
|
104
|
+
def close(self) -> None:
|
|
105
|
+
self._http.close()
|
|
106
|
+
self._api.close()
|
|
107
|
+
|
|
108
|
+
def _send(self, http: httpx.Client, method: str, path: str, *, idempotency_key: str | None = None,
|
|
109
|
+
create: bool = False, **kw: Any) -> httpx.Response:
|
|
110
|
+
if create or idempotency_key:
|
|
111
|
+
kw["headers"] = {"Idempotency-Key": idempotency_key or str(uuid.uuid4())}
|
|
112
|
+
r = http.request(method, path, **kw)
|
|
113
|
+
if r.status_code == 429:
|
|
114
|
+
after = r.headers.get("retry-after")
|
|
115
|
+
wait = 1 if after is None else _int(after)
|
|
116
|
+
if wait is not None and 0 <= wait <= 60:
|
|
117
|
+
time.sleep(wait)
|
|
118
|
+
r = http.request(method, path, **kw)
|
|
119
|
+
if r.status_code >= 400:
|
|
120
|
+
raise _error(r)
|
|
121
|
+
return r
|
|
122
|
+
|
|
123
|
+
def _json(self, http: httpx.Client, method: str, path: str, **kw: Any) -> Any:
|
|
124
|
+
r = self._send(http, method, path, **kw)
|
|
125
|
+
return r.json() if r.content else None
|
|
126
|
+
|
|
127
|
+
def scrape(self, url: str, *, idempotency_key: str | None = None, **params: Any) -> Result:
|
|
128
|
+
r = self._send(self._http, "POST", "/v1", idempotency_key=idempotency_key, create=True,
|
|
129
|
+
json={"url": url, **_envelope(params)})
|
|
130
|
+
return Result(r.status_code, r.content, _headers(r.headers))
|
|
131
|
+
|
|
132
|
+
def get_tier(self, host: str, **query: Any) -> dict:
|
|
133
|
+
return self._json(self._http, "GET", "/v1/tier", params={"host": host, **query})
|
|
134
|
+
|
|
135
|
+
def get_domain_stats(self, host: str, **query: Any) -> dict:
|
|
136
|
+
return self._json(self._http, "GET", "/v1/stats/domain", params={"host": host, **query})
|
|
137
|
+
|
|
138
|
+
def get_account(self) -> dict:
|
|
139
|
+
return self._json(self._api, "GET", "/v1/account")
|
|
140
|
+
|
|
141
|
+
def get_usage(self, **query: Any) -> dict:
|
|
142
|
+
return self._json(self._api, "GET", "/v1/account/usage", params=query)
|
|
143
|
+
|
|
144
|
+
def rotate_webhook_secret(self) -> dict:
|
|
145
|
+
return self._json(self._api, "POST", "/v1/account/webhook-secret/rotate")
|
|
146
|
+
|
|
147
|
+
def map_site(self, url: str, *, idempotency_key: str | None = None, **params: Any) -> dict:
|
|
148
|
+
return self._json(self._http, "POST", "/v1/map", idempotency_key=idempotency_key, create=True,
|
|
149
|
+
json={"url": url, **params})
|
|
150
|
+
|
|
151
|
+
def create_batch(self, urls: list[str], *, idempotency_key: str | None = None, **params: Any) -> dict:
|
|
152
|
+
return self._json(self._api, "POST", "/v1/batches", idempotency_key=idempotency_key, create=True,
|
|
153
|
+
json={"urls": urls, **_envelope(params)})
|
|
154
|
+
|
|
155
|
+
def quote_batch(self, urls: list[str], **params: Any) -> dict:
|
|
156
|
+
return self._json(self._api, "POST", "/v1/batches/quote", json={"urls": urls, **_envelope(params)})
|
|
157
|
+
|
|
158
|
+
def list_batches(self, **query: Any) -> dict:
|
|
159
|
+
return self._json(self._api, "GET", "/v1/batches", params=query)
|
|
160
|
+
|
|
161
|
+
def get_batch(self, id: str) -> dict:
|
|
162
|
+
return self._json(self._api, "GET", f"/v1/batches/{_id(id)}")
|
|
163
|
+
|
|
164
|
+
def list_batch_items(self, id: str, **query: Any) -> dict:
|
|
165
|
+
return self._json(self._api, "GET", f"/v1/batches/{_id(id)}/items", params=query)
|
|
166
|
+
|
|
167
|
+
def cancel_batch(self, id: str) -> dict:
|
|
168
|
+
return self._json(self._api, "POST", f"/v1/batches/{_id(id)}/cancel")
|
|
169
|
+
|
|
170
|
+
def create_monitor(self, *, idempotency_key: str | None = None, **body: Any) -> dict:
|
|
171
|
+
return self._json(self._api, "POST", "/v1/monitors", idempotency_key=idempotency_key, create=True,
|
|
172
|
+
json=body)
|
|
173
|
+
|
|
174
|
+
def list_monitors(self, **query: Any) -> dict:
|
|
175
|
+
return self._json(self._api, "GET", "/v1/monitors", params=query)
|
|
176
|
+
|
|
177
|
+
def get_monitor(self, id: str) -> dict:
|
|
178
|
+
return self._json(self._api, "GET", f"/v1/monitors/{_id(id)}")
|
|
179
|
+
|
|
180
|
+
def update_monitor(self, id: str, **body: Any) -> dict:
|
|
181
|
+
return self._json(self._api, "PATCH", f"/v1/monitors/{_id(id)}", json=body)
|
|
182
|
+
|
|
183
|
+
def delete_monitor(self, id: str) -> None:
|
|
184
|
+
self._json(self._api, "DELETE", f"/v1/monitors/{_id(id)}")
|
|
185
|
+
|
|
186
|
+
def run_monitor(self, id: str) -> dict:
|
|
187
|
+
return self._json(self._api, "POST", f"/v1/monitors/{_id(id)}/run")
|
|
188
|
+
|
|
189
|
+
def list_monitor_checks(self, id: str, **query: Any) -> dict:
|
|
190
|
+
return self._json(self._api, "GET", f"/v1/monitors/{_id(id)}/checks", params=query)
|
|
191
|
+
|
|
192
|
+
def wait_batch(self, id: str, *, timeout: float = 3600.0, poll: float = 2.0) -> dict:
|
|
193
|
+
end = time.monotonic() + timeout
|
|
194
|
+
while True:
|
|
195
|
+
batch = self.get_batch(id)
|
|
196
|
+
if batch.get("status") in ("done", "failed", "canceled"):
|
|
197
|
+
return batch
|
|
198
|
+
if time.monotonic() + poll > end:
|
|
199
|
+
raise TimeoutError(f"batch {id} still {batch.get('status')} after {timeout:g} s")
|
|
200
|
+
time.sleep(poll)
|
|
201
|
+
|
|
202
|
+
def read_results(self, items: list[dict]) -> list[bytes]:
|
|
203
|
+
links = [item["result_url"] for item in items if item.get("result_url")]
|
|
204
|
+
if not links:
|
|
205
|
+
return []
|
|
206
|
+
|
|
207
|
+
def get(link: str) -> bytes:
|
|
208
|
+
r = plain.get(link)
|
|
209
|
+
if r.status_code >= 400:
|
|
210
|
+
raise _error(r)
|
|
211
|
+
return r.content
|
|
212
|
+
|
|
213
|
+
with httpx.Client(timeout=httpx.Timeout(self._timeout)) as plain, \
|
|
214
|
+
ThreadPoolExecutor(max_workers=min(8, len(links))) as pool:
|
|
215
|
+
return list(pool.map(get, links))
|
|
216
|
+
|
|
217
|
+
def batch_results(self, id: str) -> Iterator[tuple[dict, bytes]]:
|
|
218
|
+
cursor = None
|
|
219
|
+
while True:
|
|
220
|
+
page = self.list_batch_items(id, limit=100, **({"cursor": cursor} if cursor else {}))
|
|
221
|
+
items = [item for item in page.get("items") or [] if item.get("result_url")]
|
|
222
|
+
yield from zip(items, self.read_results(items))
|
|
223
|
+
cursor = page.get("next_cursor")
|
|
224
|
+
if not cursor:
|
|
225
|
+
return
|
|
226
|
+
|
|
227
|
+
def read_pages(self, urls: str | list[str], *, crawl: dict | None = None, continue_on_failure: bool = False,
|
|
228
|
+
**params: Any) -> Iterator[tuple[str, dict]]:
|
|
229
|
+
urls = [urls] if isinstance(urls, str) else list(urls)
|
|
230
|
+
if crawl is not None:
|
|
231
|
+
if len(urls) != 1:
|
|
232
|
+
raise ValueError("a crawl starts from exactly one URL")
|
|
233
|
+
batch = self.create_batch(urls, crawl=crawl, **{"response_types": _default_type(params), **params})
|
|
234
|
+
self.wait_batch(batch["id"])
|
|
235
|
+
for item, body in self.batch_results(batch["id"]):
|
|
236
|
+
yield body.decode("utf-8", errors="replace"), {
|
|
237
|
+
"source": item.get("url"), "depth": item.get("depth"), "target_status": item.get("target_status")}
|
|
238
|
+
return
|
|
239
|
+
for url in urls:
|
|
240
|
+
try:
|
|
241
|
+
r = self.scrape(url, **{"response_types": _default_type(params), **params})
|
|
242
|
+
except MegalaniaError as e:
|
|
243
|
+
if not continue_on_failure:
|
|
244
|
+
raise
|
|
245
|
+
logging.getLogger("megalania").warning("skipped a page: %s (request %s)", e.code, e.request_id)
|
|
246
|
+
continue
|
|
247
|
+
yield r.text, {"source": url, "request_id": r.headers.request_id,
|
|
248
|
+
"credits_charged": r.headers.credits_charged, "target_status": r.headers.target_status}
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _envelope(params: dict) -> dict:
|
|
252
|
+
schema = params.get("schema")
|
|
253
|
+
return params if schema is None or isinstance(schema, str) else {**params, "schema": json.dumps(schema)}
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _default_type(params: dict) -> str:
|
|
257
|
+
return "json" if "schema" in params else "markdown"
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _id(v: str) -> str:
|
|
261
|
+
return urllib.parse.quote(str(v), safe="")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _int(v: str | None) -> int | None:
|
|
265
|
+
try:
|
|
266
|
+
return int(v) if v is not None else None
|
|
267
|
+
except ValueError:
|
|
268
|
+
return None
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _headers(h: httpx.Headers) -> Headers:
|
|
272
|
+
values: dict[str, Any] = {}
|
|
273
|
+
for f in dataclasses.fields(Headers):
|
|
274
|
+
v = h.get(header_name(f.name))
|
|
275
|
+
if v is not None:
|
|
276
|
+
values[f.name] = _int(v) if int in typing.get_args(f.type) else v
|
|
277
|
+
return Headers(**values)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _error(r: httpx.Response) -> MegalaniaError:
|
|
281
|
+
rid = r.headers.get("x-request-id")
|
|
282
|
+
try:
|
|
283
|
+
e = r.json()["error"]
|
|
284
|
+
return MegalaniaError(r.status_code, e.get("code"), e.get("message") or r.text[:500], e.get("field"),
|
|
285
|
+
rid, e.get("report_url"), _headers(r.headers))
|
|
286
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
287
|
+
return MegalaniaError(r.status_code, None, r.text[:500] or f"HTTP {r.status_code}", None, rid, None,
|
|
288
|
+
_headers(r.headers))
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
__all__ = ["Headers", "Megalania", "MegalaniaError", "Result"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Contains methods for accessing the API"""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Contains endpoint functions for accessing the API"""
|