gainflow 0.1.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.
- gainflow/__init__.py +13 -0
- gainflow/async_client.py +236 -0
- gainflow/client.py +226 -0
- gainflow/errors.py +80 -0
- gainflow/py.typed +1 -0
- gainflow-0.1.0.dist-info/METADATA +93 -0
- gainflow-0.1.0.dist-info/RECORD +9 -0
- gainflow-0.1.0.dist-info/WHEEL +4 -0
- gainflow-0.1.0.dist-info/licenses/LICENSE +21 -0
gainflow/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from gainflow.async_client import AsyncGainflowClient
|
|
2
|
+
from gainflow.client import GainflowClient
|
|
3
|
+
from gainflow.errors import DEFAULT_BASE_URL, SDK_VERSION, GainflowApiError
|
|
4
|
+
|
|
5
|
+
__version__ = SDK_VERSION
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"DEFAULT_BASE_URL",
|
|
9
|
+
"AsyncGainflowClient",
|
|
10
|
+
"GainflowApiError",
|
|
11
|
+
"GainflowClient",
|
|
12
|
+
"__version__",
|
|
13
|
+
]
|
gainflow/async_client.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from collections.abc import Sequence
|
|
3
|
+
from typing import Any
|
|
4
|
+
from urllib.parse import quote
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
from gainflow.errors import (
|
|
9
|
+
RETRYABLE_STATUSES,
|
|
10
|
+
SDK_VERSION,
|
|
11
|
+
decode_response,
|
|
12
|
+
parse_retry_after,
|
|
13
|
+
qs,
|
|
14
|
+
resolve_api_key,
|
|
15
|
+
resolve_base_url,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _AsyncResource:
|
|
20
|
+
def __init__(self, client: "AsyncGainflowClient") -> None:
|
|
21
|
+
self._c = client
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AsyncBusinessesResource(_AsyncResource):
|
|
25
|
+
async def search(self, **kwargs: object) -> dict[str, Any]:
|
|
26
|
+
return await self._c.request("POST", "/v1/businesses/search", json=dict(kwargs))
|
|
27
|
+
|
|
28
|
+
async def get(self, business_id: str) -> dict[str, Any]:
|
|
29
|
+
return await self._c.request("GET", f"/v1/businesses/{quote(business_id, safe='')}")
|
|
30
|
+
|
|
31
|
+
async def enrich(self, business_id: str) -> dict[str, Any]:
|
|
32
|
+
return await self._c.request("POST", f"/v1/businesses/{quote(business_id, safe='')}/enrich")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AsyncWebhooksResource(_AsyncResource):
|
|
36
|
+
async def list(self, *, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:
|
|
37
|
+
return await self._c.request("GET", f"/v1/webhooks{qs({'limit': limit, 'cursor': cursor})}")
|
|
38
|
+
|
|
39
|
+
async def create(self, *, url: str, events: Sequence[str]) -> dict[str, Any]:
|
|
40
|
+
return await self._c.request(
|
|
41
|
+
"POST", "/v1/webhooks", json={"url": url, "events": list(events)}
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
async def delete(self, webhook_id: str) -> dict[str, Any]:
|
|
45
|
+
return await self._c.request("DELETE", f"/v1/webhooks/{quote(webhook_id, safe='')}")
|
|
46
|
+
|
|
47
|
+
async def deliveries(
|
|
48
|
+
self, webhook_id: str, *, limit: int | None = None, cursor: str | None = None
|
|
49
|
+
) -> dict[str, Any]:
|
|
50
|
+
q = qs({"limit": limit, "cursor": cursor})
|
|
51
|
+
return await self._c.request(
|
|
52
|
+
"GET", f"/v1/webhooks/{quote(webhook_id, safe='')}/deliveries{q}"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class AsyncMonitorsResource(_AsyncResource):
|
|
57
|
+
async def list(self, *, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:
|
|
58
|
+
return await self._c.request("GET", f"/v1/monitors{qs({'limit': limit, 'cursor': cursor})}")
|
|
59
|
+
|
|
60
|
+
async def create(self, **kwargs: object) -> dict[str, Any]:
|
|
61
|
+
return await self._c.request("POST", "/v1/monitors", json=dict(kwargs))
|
|
62
|
+
|
|
63
|
+
async def update(self, monitor_id: str, **kwargs: object) -> dict[str, Any]:
|
|
64
|
+
path = f"/v1/monitors/{quote(monitor_id, safe='')}"
|
|
65
|
+
return await self._c.request("PATCH", path, json=dict(kwargs))
|
|
66
|
+
|
|
67
|
+
async def delete(self, monitor_id: str) -> dict[str, Any]:
|
|
68
|
+
return await self._c.request("DELETE", f"/v1/monitors/{quote(monitor_id, safe='')}")
|
|
69
|
+
|
|
70
|
+
async def events(
|
|
71
|
+
self, monitor_id: str, *, limit: int | None = None, cursor: str | None = None
|
|
72
|
+
) -> dict[str, Any]:
|
|
73
|
+
q = qs({"limit": limit, "cursor": cursor})
|
|
74
|
+
return await self._c.request("GET", f"/v1/monitors/{quote(monitor_id, safe='')}/events{q}")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class AsyncBatchesResource(_AsyncResource):
|
|
78
|
+
async def list(self, *, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:
|
|
79
|
+
return await self._c.request("GET", f"/v1/batches{qs({'limit': limit, 'cursor': cursor})}")
|
|
80
|
+
|
|
81
|
+
async def create(self, **kwargs: object) -> dict[str, Any]:
|
|
82
|
+
return await self._c.request("POST", "/v1/batches", json=dict(kwargs))
|
|
83
|
+
|
|
84
|
+
async def get(self, batch_id: str, *, limit: int | None = None) -> dict[str, Any]:
|
|
85
|
+
return await self._c.request(
|
|
86
|
+
"GET", f"/v1/batches/{quote(batch_id, safe='')}{qs({'limit': limit})}"
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
async def cancel(self, batch_id: str) -> dict[str, Any]:
|
|
90
|
+
return await self._c.request("POST", f"/v1/batches/{quote(batch_id, safe='')}/cancel")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class AsyncCrawlsResource(_AsyncResource):
|
|
94
|
+
async def list(self, *, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:
|
|
95
|
+
return await self._c.request("GET", f"/v1/crawls{qs({'limit': limit, 'cursor': cursor})}")
|
|
96
|
+
|
|
97
|
+
async def create(self, **kwargs: object) -> dict[str, Any]:
|
|
98
|
+
return await self._c.request("POST", "/v1/crawl", json=dict(kwargs))
|
|
99
|
+
|
|
100
|
+
async def get(self, crawl_id: str, *, limit: int | None = None) -> dict[str, Any]:
|
|
101
|
+
return await self._c.request(
|
|
102
|
+
"GET", f"/v1/crawls/{quote(crawl_id, safe='')}{qs({'limit': limit})}"
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
async def cancel(self, crawl_id: str) -> dict[str, Any]:
|
|
106
|
+
return await self._c.request("POST", f"/v1/crawls/{quote(crawl_id, safe='')}/cancel")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class AsyncAccountResource(_AsyncResource):
|
|
110
|
+
async def balance(self) -> dict[str, Any]:
|
|
111
|
+
return await self._c.request("GET", "/v1/account/balance")
|
|
112
|
+
|
|
113
|
+
async def usage(self, *, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:
|
|
114
|
+
return await self._c.request(
|
|
115
|
+
"GET", f"/v1/account/usage{qs({'limit': limit, 'cursor': cursor})}"
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
async def list_api_keys(
|
|
119
|
+
self, *, limit: int | None = None, cursor: str | None = None
|
|
120
|
+
) -> dict[str, Any]:
|
|
121
|
+
q = qs({"limit": limit, "cursor": cursor})
|
|
122
|
+
return await self._c.request("GET", f"/v1/account/api-keys{q}")
|
|
123
|
+
|
|
124
|
+
async def create_api_key(
|
|
125
|
+
self, *, name: str, scopes: Sequence[str] | None = None
|
|
126
|
+
) -> dict[str, Any]:
|
|
127
|
+
payload: dict[str, object] = {"name": name}
|
|
128
|
+
if scopes is not None:
|
|
129
|
+
payload["scopes"] = list(scopes)
|
|
130
|
+
return await self._c.request("POST", "/v1/account/api-keys", json=payload)
|
|
131
|
+
|
|
132
|
+
async def revoke_api_key(self, key_id: str) -> dict[str, Any]:
|
|
133
|
+
return await self._c.request("DELETE", f"/v1/account/api-keys/{quote(key_id, safe='')}")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class AsyncBillingResource(_AsyncResource):
|
|
137
|
+
async def checkout(self, *, plan: str, success_url: str, cancel_url: str) -> dict[str, Any]:
|
|
138
|
+
return await self._c.request(
|
|
139
|
+
"POST",
|
|
140
|
+
"/v1/billing/checkout",
|
|
141
|
+
json={"plan": plan, "success_url": success_url, "cancel_url": cancel_url},
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
async def portal(self, *, return_url: str) -> dict[str, Any]:
|
|
145
|
+
return await self._c.request("POST", "/v1/billing/portal", json={"return_url": return_url})
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class AsyncGainflowClient:
|
|
149
|
+
def __init__(
|
|
150
|
+
self,
|
|
151
|
+
api_key: str | None = None,
|
|
152
|
+
*,
|
|
153
|
+
base_url: str | None = None,
|
|
154
|
+
timeout: float = 35.0,
|
|
155
|
+
max_retries: int = 2,
|
|
156
|
+
http_client: httpx.AsyncClient | None = None,
|
|
157
|
+
) -> None:
|
|
158
|
+
self._api_key = resolve_api_key(api_key)
|
|
159
|
+
self._base_url = resolve_base_url(base_url)
|
|
160
|
+
self._max_retries = max(0, min(max_retries, 5))
|
|
161
|
+
self._owns_client = http_client is None
|
|
162
|
+
self._http = http_client or httpx.AsyncClient(timeout=timeout)
|
|
163
|
+
|
|
164
|
+
self.businesses = AsyncBusinessesResource(self)
|
|
165
|
+
self.webhooks = AsyncWebhooksResource(self)
|
|
166
|
+
self.monitors = AsyncMonitorsResource(self)
|
|
167
|
+
self.batches = AsyncBatchesResource(self)
|
|
168
|
+
self.crawls = AsyncCrawlsResource(self)
|
|
169
|
+
self.account = AsyncAccountResource(self)
|
|
170
|
+
self.billing = AsyncBillingResource(self)
|
|
171
|
+
|
|
172
|
+
async def aclose(self) -> None:
|
|
173
|
+
if self._owns_client:
|
|
174
|
+
await self._http.aclose()
|
|
175
|
+
|
|
176
|
+
async def __aenter__(self) -> "AsyncGainflowClient":
|
|
177
|
+
return self
|
|
178
|
+
|
|
179
|
+
async def __aexit__(self, *_args: object) -> None:
|
|
180
|
+
await self.aclose()
|
|
181
|
+
|
|
182
|
+
async def request(
|
|
183
|
+
self,
|
|
184
|
+
method: str,
|
|
185
|
+
path: str,
|
|
186
|
+
*,
|
|
187
|
+
json: dict[str, object] | None = None,
|
|
188
|
+
idempotency_key: str | None = None,
|
|
189
|
+
) -> dict[str, Any]:
|
|
190
|
+
headers: dict[str, str] = {
|
|
191
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
192
|
+
"Accept": "application/json",
|
|
193
|
+
"User-Agent": f"gainflow-python/{SDK_VERSION}",
|
|
194
|
+
}
|
|
195
|
+
if idempotency_key:
|
|
196
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
197
|
+
|
|
198
|
+
url = f"{self._base_url}{path if path.startswith('/') else f'/{path}'}"
|
|
199
|
+
for attempt in range(self._max_retries + 1):
|
|
200
|
+
try:
|
|
201
|
+
resp = await self._http.request(method, url, headers=headers, json=json)
|
|
202
|
+
except httpx.TransportError:
|
|
203
|
+
if attempt < self._max_retries:
|
|
204
|
+
await asyncio.sleep(0.25 * (2**attempt))
|
|
205
|
+
continue
|
|
206
|
+
raise
|
|
207
|
+
|
|
208
|
+
if resp.status_code in RETRYABLE_STATUSES and attempt < self._max_retries:
|
|
209
|
+
retry_after = parse_retry_after(resp.headers.get("retry-after"))
|
|
210
|
+
await asyncio.sleep(retry_after if retry_after is not None else 0.3 * (2**attempt))
|
|
211
|
+
continue
|
|
212
|
+
return decode_response(resp)
|
|
213
|
+
|
|
214
|
+
raise RuntimeError("Gainflow request exhausted retries")
|
|
215
|
+
|
|
216
|
+
async def scrape(
|
|
217
|
+
self,
|
|
218
|
+
url: str,
|
|
219
|
+
*,
|
|
220
|
+
idempotency_key: str | None = None,
|
|
221
|
+
**kwargs: object,
|
|
222
|
+
) -> dict[str, Any]:
|
|
223
|
+
payload: dict[str, object] = {"url": url, **kwargs}
|
|
224
|
+
return await self.request(
|
|
225
|
+
"POST", "/v1/scrape", json=payload, idempotency_key=idempotency_key
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
async def map(
|
|
229
|
+
self,
|
|
230
|
+
url: str,
|
|
231
|
+
*,
|
|
232
|
+
idempotency_key: str | None = None,
|
|
233
|
+
**kwargs: object,
|
|
234
|
+
) -> dict[str, Any]:
|
|
235
|
+
payload: dict[str, object] = {"url": url, **kwargs}
|
|
236
|
+
return await self.request("POST", "/v1/map", json=payload, idempotency_key=idempotency_key)
|
gainflow/client.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from collections.abc import Sequence
|
|
3
|
+
from typing import Any
|
|
4
|
+
from urllib.parse import quote
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
from gainflow.errors import (
|
|
9
|
+
RETRYABLE_STATUSES,
|
|
10
|
+
SDK_VERSION,
|
|
11
|
+
decode_response,
|
|
12
|
+
parse_retry_after,
|
|
13
|
+
qs,
|
|
14
|
+
resolve_api_key,
|
|
15
|
+
resolve_base_url,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _Resource:
|
|
20
|
+
def __init__(self, client: "GainflowClient") -> None:
|
|
21
|
+
self._c = client
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class BusinessesResource(_Resource):
|
|
25
|
+
def search(self, **kwargs: object) -> dict[str, Any]:
|
|
26
|
+
return self._c.request("POST", "/v1/businesses/search", json=dict(kwargs))
|
|
27
|
+
|
|
28
|
+
def get(self, business_id: str) -> dict[str, Any]:
|
|
29
|
+
return self._c.request("GET", f"/v1/businesses/{quote(business_id, safe='')}")
|
|
30
|
+
|
|
31
|
+
def enrich(self, business_id: str) -> dict[str, Any]:
|
|
32
|
+
return self._c.request("POST", f"/v1/businesses/{quote(business_id, safe='')}/enrich")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class WebhooksResource(_Resource):
|
|
36
|
+
def list(self, *, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:
|
|
37
|
+
return self._c.request("GET", f"/v1/webhooks{qs({'limit': limit, 'cursor': cursor})}")
|
|
38
|
+
|
|
39
|
+
def create(self, *, url: str, events: Sequence[str]) -> dict[str, Any]:
|
|
40
|
+
return self._c.request("POST", "/v1/webhooks", json={"url": url, "events": list(events)})
|
|
41
|
+
|
|
42
|
+
def delete(self, webhook_id: str) -> dict[str, Any]:
|
|
43
|
+
return self._c.request("DELETE", f"/v1/webhooks/{quote(webhook_id, safe='')}")
|
|
44
|
+
|
|
45
|
+
def deliveries(
|
|
46
|
+
self, webhook_id: str, *, limit: int | None = None, cursor: str | None = None
|
|
47
|
+
) -> dict[str, Any]:
|
|
48
|
+
q = qs({"limit": limit, "cursor": cursor})
|
|
49
|
+
return self._c.request("GET", f"/v1/webhooks/{quote(webhook_id, safe='')}/deliveries{q}")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class MonitorsResource(_Resource):
|
|
53
|
+
def list(self, *, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:
|
|
54
|
+
return self._c.request("GET", f"/v1/monitors{qs({'limit': limit, 'cursor': cursor})}")
|
|
55
|
+
|
|
56
|
+
def create(self, **kwargs: object) -> dict[str, Any]:
|
|
57
|
+
return self._c.request("POST", "/v1/monitors", json=dict(kwargs))
|
|
58
|
+
|
|
59
|
+
def update(self, monitor_id: str, **kwargs: object) -> dict[str, Any]:
|
|
60
|
+
path = f"/v1/monitors/{quote(monitor_id, safe='')}"
|
|
61
|
+
return self._c.request("PATCH", path, json=dict(kwargs))
|
|
62
|
+
|
|
63
|
+
def delete(self, monitor_id: str) -> dict[str, Any]:
|
|
64
|
+
return self._c.request("DELETE", f"/v1/monitors/{quote(monitor_id, safe='')}")
|
|
65
|
+
|
|
66
|
+
def events(
|
|
67
|
+
self, monitor_id: str, *, limit: int | None = None, cursor: str | None = None
|
|
68
|
+
) -> dict[str, Any]:
|
|
69
|
+
q = qs({"limit": limit, "cursor": cursor})
|
|
70
|
+
return self._c.request("GET", f"/v1/monitors/{quote(monitor_id, safe='')}/events{q}")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class BatchesResource(_Resource):
|
|
74
|
+
def list(self, *, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:
|
|
75
|
+
return self._c.request("GET", f"/v1/batches{qs({'limit': limit, 'cursor': cursor})}")
|
|
76
|
+
|
|
77
|
+
def create(self, **kwargs: object) -> dict[str, Any]:
|
|
78
|
+
return self._c.request("POST", "/v1/batches", json=dict(kwargs))
|
|
79
|
+
|
|
80
|
+
def get(self, batch_id: str, *, limit: int | None = None) -> dict[str, Any]:
|
|
81
|
+
return self._c.request(
|
|
82
|
+
"GET", f"/v1/batches/{quote(batch_id, safe='')}{qs({'limit': limit})}"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def cancel(self, batch_id: str) -> dict[str, Any]:
|
|
86
|
+
return self._c.request("POST", f"/v1/batches/{quote(batch_id, safe='')}/cancel")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class CrawlsResource(_Resource):
|
|
90
|
+
def list(self, *, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:
|
|
91
|
+
return self._c.request("GET", f"/v1/crawls{qs({'limit': limit, 'cursor': cursor})}")
|
|
92
|
+
|
|
93
|
+
def create(self, **kwargs: object) -> dict[str, Any]:
|
|
94
|
+
return self._c.request("POST", "/v1/crawl", json=dict(kwargs))
|
|
95
|
+
|
|
96
|
+
def get(self, crawl_id: str, *, limit: int | None = None) -> dict[str, Any]:
|
|
97
|
+
return self._c.request(
|
|
98
|
+
"GET", f"/v1/crawls/{quote(crawl_id, safe='')}{qs({'limit': limit})}"
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
def cancel(self, crawl_id: str) -> dict[str, Any]:
|
|
102
|
+
return self._c.request("POST", f"/v1/crawls/{quote(crawl_id, safe='')}/cancel")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class AccountResource(_Resource):
|
|
106
|
+
def balance(self) -> dict[str, Any]:
|
|
107
|
+
return self._c.request("GET", "/v1/account/balance")
|
|
108
|
+
|
|
109
|
+
def usage(self, *, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:
|
|
110
|
+
return self._c.request("GET", f"/v1/account/usage{qs({'limit': limit, 'cursor': cursor})}")
|
|
111
|
+
|
|
112
|
+
def list_api_keys(
|
|
113
|
+
self, *, limit: int | None = None, cursor: str | None = None
|
|
114
|
+
) -> dict[str, Any]:
|
|
115
|
+
q = qs({"limit": limit, "cursor": cursor})
|
|
116
|
+
return self._c.request("GET", f"/v1/account/api-keys{q}")
|
|
117
|
+
|
|
118
|
+
def create_api_key(self, *, name: str, scopes: Sequence[str] | None = None) -> dict[str, Any]:
|
|
119
|
+
payload: dict[str, object] = {"name": name}
|
|
120
|
+
if scopes is not None:
|
|
121
|
+
payload["scopes"] = list(scopes)
|
|
122
|
+
return self._c.request("POST", "/v1/account/api-keys", json=payload)
|
|
123
|
+
|
|
124
|
+
def revoke_api_key(self, key_id: str) -> dict[str, Any]:
|
|
125
|
+
return self._c.request("DELETE", f"/v1/account/api-keys/{quote(key_id, safe='')}")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class BillingResource(_Resource):
|
|
129
|
+
def checkout(self, *, plan: str, success_url: str, cancel_url: str) -> dict[str, Any]:
|
|
130
|
+
return self._c.request(
|
|
131
|
+
"POST",
|
|
132
|
+
"/v1/billing/checkout",
|
|
133
|
+
json={"plan": plan, "success_url": success_url, "cancel_url": cancel_url},
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
def portal(self, *, return_url: str) -> dict[str, Any]:
|
|
137
|
+
return self._c.request("POST", "/v1/billing/portal", json={"return_url": return_url})
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class GainflowClient:
|
|
141
|
+
def __init__(
|
|
142
|
+
self,
|
|
143
|
+
api_key: str | None = None,
|
|
144
|
+
*,
|
|
145
|
+
base_url: str | None = None,
|
|
146
|
+
timeout: float = 35.0,
|
|
147
|
+
max_retries: int = 2,
|
|
148
|
+
http_client: httpx.Client | None = None,
|
|
149
|
+
) -> None:
|
|
150
|
+
self._api_key = resolve_api_key(api_key)
|
|
151
|
+
self._base_url = resolve_base_url(base_url)
|
|
152
|
+
self._max_retries = max(0, min(max_retries, 5))
|
|
153
|
+
self._owns_client = http_client is None
|
|
154
|
+
self._http = http_client or httpx.Client(timeout=timeout)
|
|
155
|
+
|
|
156
|
+
self.businesses = BusinessesResource(self)
|
|
157
|
+
self.webhooks = WebhooksResource(self)
|
|
158
|
+
self.monitors = MonitorsResource(self)
|
|
159
|
+
self.batches = BatchesResource(self)
|
|
160
|
+
self.crawls = CrawlsResource(self)
|
|
161
|
+
self.account = AccountResource(self)
|
|
162
|
+
self.billing = BillingResource(self)
|
|
163
|
+
|
|
164
|
+
def close(self) -> None:
|
|
165
|
+
if self._owns_client:
|
|
166
|
+
self._http.close()
|
|
167
|
+
|
|
168
|
+
def __enter__(self) -> "GainflowClient":
|
|
169
|
+
return self
|
|
170
|
+
|
|
171
|
+
def __exit__(self, *_args: object) -> None:
|
|
172
|
+
self.close()
|
|
173
|
+
|
|
174
|
+
def request(
|
|
175
|
+
self,
|
|
176
|
+
method: str,
|
|
177
|
+
path: str,
|
|
178
|
+
*,
|
|
179
|
+
json: dict[str, object] | None = None,
|
|
180
|
+
idempotency_key: str | None = None,
|
|
181
|
+
) -> dict[str, Any]:
|
|
182
|
+
headers: dict[str, str] = {
|
|
183
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
184
|
+
"Accept": "application/json",
|
|
185
|
+
"User-Agent": f"gainflow-python/{SDK_VERSION}",
|
|
186
|
+
}
|
|
187
|
+
if idempotency_key:
|
|
188
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
189
|
+
|
|
190
|
+
url = f"{self._base_url}{path if path.startswith('/') else f'/{path}'}"
|
|
191
|
+
for attempt in range(self._max_retries + 1):
|
|
192
|
+
try:
|
|
193
|
+
resp = self._http.request(method, url, headers=headers, json=json)
|
|
194
|
+
except httpx.TransportError:
|
|
195
|
+
if attempt < self._max_retries:
|
|
196
|
+
time.sleep(0.25 * (2**attempt))
|
|
197
|
+
continue
|
|
198
|
+
raise
|
|
199
|
+
|
|
200
|
+
if resp.status_code in RETRYABLE_STATUSES and attempt < self._max_retries:
|
|
201
|
+
retry_after = parse_retry_after(resp.headers.get("retry-after"))
|
|
202
|
+
time.sleep(retry_after if retry_after is not None else 0.3 * (2**attempt))
|
|
203
|
+
continue
|
|
204
|
+
return decode_response(resp)
|
|
205
|
+
|
|
206
|
+
raise RuntimeError("Gainflow request exhausted retries")
|
|
207
|
+
|
|
208
|
+
def scrape(
|
|
209
|
+
self,
|
|
210
|
+
url: str,
|
|
211
|
+
*,
|
|
212
|
+
idempotency_key: str | None = None,
|
|
213
|
+
**kwargs: object,
|
|
214
|
+
) -> dict[str, Any]:
|
|
215
|
+
payload: dict[str, object] = {"url": url, **kwargs}
|
|
216
|
+
return self.request("POST", "/v1/scrape", json=payload, idempotency_key=idempotency_key)
|
|
217
|
+
|
|
218
|
+
def map(
|
|
219
|
+
self,
|
|
220
|
+
url: str,
|
|
221
|
+
*,
|
|
222
|
+
idempotency_key: str | None = None,
|
|
223
|
+
**kwargs: object,
|
|
224
|
+
) -> dict[str, Any]:
|
|
225
|
+
payload: dict[str, object] = {"url": url, **kwargs}
|
|
226
|
+
return self.request("POST", "/v1/map", json=payload, idempotency_key=idempotency_key)
|
gainflow/errors.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Any, cast
|
|
4
|
+
from urllib.parse import urlencode
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
DEFAULT_BASE_URL = "https://api.gainflow.ai"
|
|
9
|
+
SDK_VERSION = "0.1.0"
|
|
10
|
+
RETRYABLE_STATUSES = frozenset({408, 429, 502, 503, 504})
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class GainflowApiError(Exception):
|
|
15
|
+
status: int
|
|
16
|
+
code: str
|
|
17
|
+
title: str
|
|
18
|
+
request_id: str
|
|
19
|
+
detail: str | None = None
|
|
20
|
+
retry_after_sec: int | None = None
|
|
21
|
+
|
|
22
|
+
def __str__(self) -> str:
|
|
23
|
+
msg = f"{self.title}: {self.detail}" if self.detail else self.title
|
|
24
|
+
return f"[{self.status} {self.code}] {msg} (request_id={self.request_id})"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def resolve_api_key(api_key: str | None) -> str:
|
|
28
|
+
resolved = (api_key or os.environ.get("GAINFLOW_API_KEY") or "").strip()
|
|
29
|
+
if not resolved:
|
|
30
|
+
raise ValueError(
|
|
31
|
+
"Gainflow client requires an API key. Pass api_key=... or set GAINFLOW_API_KEY."
|
|
32
|
+
)
|
|
33
|
+
return resolved
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def resolve_base_url(base_url: str | None) -> str:
|
|
37
|
+
resolved = (base_url or os.environ.get("GAINFLOW_BASE_URL") or DEFAULT_BASE_URL).strip()
|
|
38
|
+
return resolved.rstrip("/")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def qs(params: dict[str, object]) -> str:
|
|
42
|
+
clean = {k: str(v) for k, v in params.items() if v is not None}
|
|
43
|
+
return f"?{urlencode(clean)}" if clean else ""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def parse_retry_after(header: str | None) -> float | None:
|
|
47
|
+
if not header:
|
|
48
|
+
return None
|
|
49
|
+
try:
|
|
50
|
+
val = float(header.strip())
|
|
51
|
+
if val >= 0:
|
|
52
|
+
return min(val, 15.0)
|
|
53
|
+
except ValueError:
|
|
54
|
+
pass
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def decode_response(resp: httpx.Response) -> dict[str, Any]:
|
|
59
|
+
data: object = {}
|
|
60
|
+
if resp.content:
|
|
61
|
+
try:
|
|
62
|
+
data = resp.json()
|
|
63
|
+
except ValueError:
|
|
64
|
+
data = {"detail": resp.text[:300]}
|
|
65
|
+
|
|
66
|
+
if resp.status_code >= 400:
|
|
67
|
+
prob = cast(dict[str, object], data) if isinstance(data, dict) else {}
|
|
68
|
+
raw_status = prob.get("status", resp.status_code)
|
|
69
|
+
status_int = raw_status if isinstance(raw_status, int) else resp.status_code
|
|
70
|
+
detail_val = prob.get("detail")
|
|
71
|
+
retry_after = parse_retry_after(resp.headers.get("retry-after"))
|
|
72
|
+
raise GainflowApiError(
|
|
73
|
+
status=status_int,
|
|
74
|
+
code=str(prob.get("code", "INTERNAL_ERROR")),
|
|
75
|
+
title=str(prob.get("title", f"HTTP {resp.status_code}")),
|
|
76
|
+
request_id=str(prob.get("request_id", resp.headers.get("x-request-id", ""))),
|
|
77
|
+
detail=str(detail_val) if detail_val else None,
|
|
78
|
+
retry_after_sec=int(retry_after) if retry_after is not None else None,
|
|
79
|
+
)
|
|
80
|
+
return cast(dict[str, Any], data) if isinstance(data, dict) else {"data": data}
|
gainflow/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: gainflow
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK (sync & async) for the Gainflow web data API
|
|
5
|
+
Project-URL: Homepage, https://gainflow.ai
|
|
6
|
+
Project-URL: Documentation, https://docs.gainflow.ai
|
|
7
|
+
License: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: ai-agents,crawl,gainflow,markdown,mcp,monitoring,web-scraping
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Requires-Dist: httpx<1.0.0,>=0.27.0
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# gainflow
|
|
24
|
+
|
|
25
|
+
Official Python SDK (sync & async) for [Gainflow](https://gainflow.ai) - hard-to-get web data for builders and AI agents.
|
|
26
|
+
|
|
27
|
+
- **Docs:** https://docs.gainflow.ai
|
|
28
|
+
- **Hosted MCP Server:** `https://mcp.gainflow.ai/mcp`
|
|
29
|
+
- **Agent Skill:** `npx skills add https://gainflow.ai`
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install gainflow
|
|
35
|
+
# or
|
|
36
|
+
uv add gainflow
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Quickstart (Sync)
|
|
40
|
+
|
|
41
|
+
Set `GAINFLOW_API_KEY` in your environment (or pass `api_key=...` explicitly):
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
export GAINFLOW_API_KEY="gf_live_..."
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from gainflow import GainflowClient
|
|
49
|
+
|
|
50
|
+
with GainflowClient() as gf:
|
|
51
|
+
page = gf.scrape(
|
|
52
|
+
"https://news.ycombinator.com",
|
|
53
|
+
formats=["markdown"],
|
|
54
|
+
parse={"titles": ".titleline > a"},
|
|
55
|
+
extract={
|
|
56
|
+
"prompt": "Extract the top 3 story titles",
|
|
57
|
+
"schema": {
|
|
58
|
+
"type": "object",
|
|
59
|
+
"properties": {"top_stories": {"type": "array", "items": {"type": "string"}}},
|
|
60
|
+
"required": ["top_stories"],
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
)
|
|
64
|
+
print(page["data"]["extracted"])
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Async Client
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import asyncio
|
|
71
|
+
from gainflow import AsyncGainflowClient
|
|
72
|
+
|
|
73
|
+
async def main() -> None:
|
|
74
|
+
async with AsyncGainflowClient() as gf:
|
|
75
|
+
page = await gf.scrape("https://example.com", render_js=True)
|
|
76
|
+
print(page["data"]["markdown"])
|
|
77
|
+
|
|
78
|
+
asyncio.run(main())
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Features
|
|
82
|
+
|
|
83
|
+
- **Scraping & PDF OCR:** `gf.scrape(url, formats=..., parse=..., extract=..., render_js=..., actions=..., ocr=..., country=..., max_age_sec=..., zdr=...)`
|
|
84
|
+
- **Site Mapping & Crawling:** `gf.map(url, search=..., limit=...)`, `gf.crawls.create(url=..., max_pages=..., max_depth=...)`
|
|
85
|
+
- **Async Batches:** `gf.batches.create(urls=...)`, `gf.batches.get(batch_id)`, `gf.batches.cancel(batch_id)`
|
|
86
|
+
- **Monitors & Webhooks:** `gf.monitors.create(...)`, `gf.webhooks.create(url=..., events=...)`
|
|
87
|
+
- **Local Businesses:** `gf.businesses.search(...)`, `gf.businesses.enrich(business_id)`
|
|
88
|
+
- **Account & Billing:** `gf.account.balance()`, `gf.account.usage()`, `gf.account.create_api_key(name=...)`, `gf.billing.checkout(...)`
|
|
89
|
+
- **Low-level Escape Hatch:** `gf.request("POST", "/v1/...", json=...)` with automatic auth and retries on `408`/`429`/`502`/`503`/`504`.
|
|
90
|
+
|
|
91
|
+
## License
|
|
92
|
+
|
|
93
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
gainflow/__init__.py,sha256=8tSn8t0QbEf5wn7KBOIXBo5ae2a6GI5dIOUghwjKLKI,331
|
|
2
|
+
gainflow/async_client.py,sha256=ez4pPE3_M5bc0586kaj5YCgwkleLHuVNi6-9ZvlTT9o,9238
|
|
3
|
+
gainflow/client.py,sha256=wvd7fEZmMwTwKjx-dGPqG_ithp57QOVKmAC7P6Y5hqo,8585
|
|
4
|
+
gainflow/errors.py,sha256=Vfk0QpGBugzGSYdfmH_JL8GVU3RaiPl0NSqosv1Xzc0,2621
|
|
5
|
+
gainflow/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
6
|
+
gainflow-0.1.0.dist-info/METADATA,sha256=xbaV3xi5pTOkMtw2l04xUp-q08_5NxmV0C-wI9D2a6I,3083
|
|
7
|
+
gainflow-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
gainflow-0.1.0.dist-info/licenses/LICENSE,sha256=1s03EmIRZDyv0pu8r3IRAjKjOkY1A22k28rmla6rZ_c,1076
|
|
9
|
+
gainflow-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Gainflow (JJJ Labs)
|
|
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.
|