flask-datacircle 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.
- flask_datacircle/__init__.py +9 -0
- flask_datacircle/blueprint.py +42 -0
- flask_datacircle/client.py +194 -0
- flask_datacircle/extension.py +137 -0
- flask_datacircle/py.typed +0 -0
- flask_datacircle/templates/flask_datacircle/best_plans.html +9 -0
- flask_datacircle-0.1.0.dist-info/METADATA +186 -0
- flask_datacircle-0.1.0.dist-info/RECORD +10 -0
- flask_datacircle-0.1.0.dist-info/WHEEL +4 -0
- flask_datacircle-0.1.0.dist-info/licenses/LICENSE +9 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Datacircle's open API in a Flask app: find the best GTM APIs. No key. https://datacircle.dev"""
|
|
2
|
+
|
|
3
|
+
from .blueprint import datacircle_blueprint
|
|
4
|
+
from .client import BASE_URL, USER_AGENT, VERSION, DatacircleClient, DatacircleError, MemoryCache
|
|
5
|
+
from .extension import Datacircle, get_client
|
|
6
|
+
|
|
7
|
+
__version__ = VERSION
|
|
8
|
+
__all__ = ["BASE_URL", "USER_AGENT", "VERSION", "Datacircle", "DatacircleClient", "DatacircleError", "MemoryCache",
|
|
9
|
+
"datacircle_blueprint", "get_client"]
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""A blueprint answering the API's four calls from your app's own address, with the API's JSON as it sent it. Register it:
|
|
2
|
+
app.register_blueprint(datacircle_blueprint, url_prefix="/datacircle")."""
|
|
3
|
+
|
|
4
|
+
from typing import Callable, Iterable
|
|
5
|
+
from urllib.parse import quote
|
|
6
|
+
|
|
7
|
+
from flask import Blueprint, Response, jsonify, request
|
|
8
|
+
|
|
9
|
+
from .client import DatacircleError
|
|
10
|
+
from .extension import get_client
|
|
11
|
+
|
|
12
|
+
datacircle_blueprint = Blueprint("datacircle", __name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _answer(path: str, names: Iterable[str]) -> Response:
|
|
16
|
+
"""The API's answer to path, sent only its own query parameters of the request's. A refusal is answered in the API's
|
|
17
|
+
status and words, Retry-After kept on a 429."""
|
|
18
|
+
try:
|
|
19
|
+
body = get_client().raw(path, {name: request.args.get(name) for name in names})
|
|
20
|
+
except DatacircleError as error:
|
|
21
|
+
response = jsonify(error.body if error.body is not None else {"error": error.message})
|
|
22
|
+
response.status_code = error.status
|
|
23
|
+
if error.retry_after:
|
|
24
|
+
response.headers["Retry-After"] = error.retry_after
|
|
25
|
+
return response
|
|
26
|
+
return Response(body, mimetype="application/json")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _route(rule: str, endpoint: str, path: Callable[..., str], names: Iterable[str] = ()) -> None:
|
|
30
|
+
def view(**kwargs: str) -> Response:
|
|
31
|
+
return _answer(path(**kwargs), names)
|
|
32
|
+
datacircle_blueprint.add_url_rule(rule, endpoint, view, methods=["GET"])
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
#: GET /apis: every API.
|
|
36
|
+
_route("/apis", "apis", lambda: "/apis")
|
|
37
|
+
#: GET /apis/<slug>/best?limit=: who is best for one API.
|
|
38
|
+
_route("/apis/<slug>/best", "best", lambda slug: f"/apis/{quote(slug, safe='')}/best", ["limit"])
|
|
39
|
+
#: GET /plans?api=&query=&sort=&limit=&offset=: plan search.
|
|
40
|
+
_route("/plans", "plans", lambda: "/plans", ["api", "query", "sort", "limit", "offset"])
|
|
41
|
+
#: GET /providers/<slug>?plans=: one provider on every API.
|
|
42
|
+
_route("/providers/<slug>", "provider", lambda slug: f"/providers/{quote(slug, safe='')}", ["plans"])
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""The client of Datacircle's open API: find the best GTM APIs. The API needs no key: https://api.datacircle.dev/v1
|
|
2
|
+
(its spec: https://api.datacircle.dev/v1/openapi.json). More at https://datacircle.dev"""
|
|
3
|
+
|
|
4
|
+
import gzip
|
|
5
|
+
import hashlib
|
|
6
|
+
import http.client
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import socket
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
from collections import OrderedDict
|
|
15
|
+
from typing import Any, Dict, Optional, Tuple
|
|
16
|
+
from urllib.parse import quote, urlencode
|
|
17
|
+
|
|
18
|
+
BASE_URL = "https://api.datacircle.dev/v1"
|
|
19
|
+
VERSION = "0.1.0"
|
|
20
|
+
USER_AGENT = f"flask-datacircle/{VERSION} (+https://datacircle.dev)"
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger("flask_datacircle")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class DatacircleError(Exception):
|
|
26
|
+
"""A call that failed. status is what the blueprint of this package answers: the API's own 400, 404 or 429 when it
|
|
27
|
+
refused the call, 502 when it failed or couldn't be reached, 504 when it didn't answer within the timeout."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, status: int, message: str, api_status: Optional[int] = None, body: Optional[Dict[str, Any]] = None,
|
|
30
|
+
retry_after: Optional[str] = None) -> None:
|
|
31
|
+
super().__init__(message)
|
|
32
|
+
self.status = status
|
|
33
|
+
#: The API's own words, like "no API has the slug bright-data".
|
|
34
|
+
self.message = message
|
|
35
|
+
#: The API's status, None when it didn't answer.
|
|
36
|
+
self.api_status = api_status
|
|
37
|
+
#: The API's JSON answer, like {"error", "slugs"} for an unknown API.
|
|
38
|
+
self.body = body
|
|
39
|
+
#: The API's Retry-After on a 429.
|
|
40
|
+
self.retry_after = retry_after
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class MemoryCache:
|
|
44
|
+
"""The cache a client keeps answers in by default: in the process, up to max_bytes of answers, the oldest dropped
|
|
45
|
+
first. Any object with get(key) and set(key, value, timeout) does instead, like Flask-Caching's Cache."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, max_bytes: int = 32 * 1024 * 1024) -> None:
|
|
48
|
+
self.max_bytes = max_bytes
|
|
49
|
+
self._kept: "OrderedDict[str, Tuple[float, bytes]]" = OrderedDict()
|
|
50
|
+
self._bytes = 0
|
|
51
|
+
self._lock = threading.Lock()
|
|
52
|
+
|
|
53
|
+
def get(self, key: str) -> Optional[bytes]:
|
|
54
|
+
with self._lock:
|
|
55
|
+
kept = self._kept.get(key)
|
|
56
|
+
if kept is None:
|
|
57
|
+
return None
|
|
58
|
+
if kept[0] <= time.monotonic():
|
|
59
|
+
self._drop(key)
|
|
60
|
+
return None
|
|
61
|
+
return kept[1]
|
|
62
|
+
|
|
63
|
+
def set(self, key: str, value: bytes, timeout: Optional[int] = None) -> None:
|
|
64
|
+
if len(value) > self.max_bytes:
|
|
65
|
+
return
|
|
66
|
+
with self._lock:
|
|
67
|
+
if key in self._kept:
|
|
68
|
+
self._drop(key)
|
|
69
|
+
self._kept[key] = (time.monotonic() + (timeout or 3600), value)
|
|
70
|
+
self._bytes += len(value)
|
|
71
|
+
while self._bytes > self.max_bytes:
|
|
72
|
+
self._drop(next(iter(self._kept)))
|
|
73
|
+
|
|
74
|
+
def clear(self) -> None:
|
|
75
|
+
with self._lock:
|
|
76
|
+
self._kept.clear()
|
|
77
|
+
self._bytes = 0
|
|
78
|
+
|
|
79
|
+
def _drop(self, key: str) -> None:
|
|
80
|
+
self._bytes -= len(self._kept.pop(key)[1])
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _unpacked(raw: bytes, encoding: Optional[str]) -> bytes:
|
|
84
|
+
# Some answers are over 10 MB whole: gzip is asked, and urllib leaves it to us to unpack.
|
|
85
|
+
return gzip.decompress(raw) if (encoding or "").strip().lower() == "gzip" else raw
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _timed_out(error: BaseException) -> bool:
|
|
89
|
+
reason = getattr(error, "reason", error)
|
|
90
|
+
return isinstance(reason, (socket.timeout, TimeoutError))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class DatacircleClient:
|
|
94
|
+
"""The four calls of Datacircle's open API. No key. Each gives the API's JSON as it is; a call that fails raises a
|
|
95
|
+
DatacircleError in the API's words.
|
|
96
|
+
|
|
97
|
+
timeout: seconds to wait for the API, the wait on a 429 too. cache: where answers are kept, a MemoryCache when left
|
|
98
|
+
out, None for no cache. cache_timeout: seconds an answer is kept."""
|
|
99
|
+
|
|
100
|
+
def __init__(self, *, base_url: str = BASE_URL, timeout: float = 30, cache: Any = "memory",
|
|
101
|
+
cache_timeout: int = 3600) -> None:
|
|
102
|
+
self.base_url = (base_url or BASE_URL).rstrip("/")
|
|
103
|
+
self.timeout = float(timeout)
|
|
104
|
+
self.cache = MemoryCache() if cache == "memory" else cache
|
|
105
|
+
self.cache_timeout = cache_timeout
|
|
106
|
+
|
|
107
|
+
def list_apis(self) -> list:
|
|
108
|
+
"""GET /apis: every API on the sheet, in its order, with its slug, its counts and its best plan."""
|
|
109
|
+
return json.loads(self.raw("/apis"))
|
|
110
|
+
|
|
111
|
+
def best_plans(self, slug: str, *, limit: Optional[int] = None) -> dict:
|
|
112
|
+
"""GET /apis/{slug}/best: the API's plans, best first by score, each with its rank. limit: 1 to 50, 10 when None."""
|
|
113
|
+
return json.loads(self.raw(f"/apis/{quote(slug, safe='')}/best", {"limit": limit}))
|
|
114
|
+
|
|
115
|
+
def search_plans(self, *, api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
|
|
116
|
+
limit: Optional[int] = None, offset: Optional[int] = None) -> dict:
|
|
117
|
+
"""GET /plans: every plan, or an API's, or those whose provider or plan name holds every word of query.
|
|
118
|
+
sort: score (the default), provider or price. limit: 1 to 50, 10 when None."""
|
|
119
|
+
return json.loads(self.raw("/plans", {"api": api, "query": query, "sort": sort, "limit": limit, "offset": offset}))
|
|
120
|
+
|
|
121
|
+
def provider(self, slug: str, *, plans: Optional[str] = None) -> dict:
|
|
122
|
+
"""GET /providers/{slug}: one provider on each API it sells, with its rank there. plans: all (the default),
|
|
123
|
+
best (its best plan on each API alone) or none (the ranks alone): a big provider's every plan is megabytes."""
|
|
124
|
+
return json.loads(self.raw(f"/providers/{quote(slug, safe='')}", {"plans": plans}))
|
|
125
|
+
|
|
126
|
+
def raw(self, path: str, params: Optional[Dict[str, Any]] = None) -> bytes:
|
|
127
|
+
"""One path of the API, its JSON answer's bytes as sent: from the cache when kept there, else called and kept."""
|
|
128
|
+
query = urlencode([(key, str(value)) for key, value in (params or {}).items() if value is not None and value != ""])
|
|
129
|
+
url = self.base_url + path + (f"?{query}" if query else "")
|
|
130
|
+
key = f"datacircle:{VERSION}:{hashlib.sha256(url.encode()).hexdigest()}"
|
|
131
|
+
if self.cache is not None:
|
|
132
|
+
try:
|
|
133
|
+
kept = self.cache.get(key)
|
|
134
|
+
except Exception: # a cache down never stops a call
|
|
135
|
+
logger.warning("datacircle: the cache can't be read", exc_info=True)
|
|
136
|
+
kept = None
|
|
137
|
+
if isinstance(kept, bytes):
|
|
138
|
+
return kept
|
|
139
|
+
body = self._call(url)
|
|
140
|
+
if self.cache is not None and self.cache_timeout:
|
|
141
|
+
try:
|
|
142
|
+
self.cache.set(key, body, self.cache_timeout)
|
|
143
|
+
except Exception: # as memcached refusing a value over its size
|
|
144
|
+
logger.warning("datacircle: the cache didn't keep %s", url, exc_info=True)
|
|
145
|
+
return body
|
|
146
|
+
|
|
147
|
+
def _call(self, url: str) -> bytes:
|
|
148
|
+
"""Calls the API: its answer's bytes when it is a 200 of JSON. A 429 is waited for once, on the API's Retry-After,
|
|
149
|
+
when the wait ends within the timeout; else it is raised at once with its Retry-After."""
|
|
150
|
+
request = urllib.request.Request(url, headers={"Accept": "application/json", "Accept-Encoding": "gzip",
|
|
151
|
+
"User-Agent": USER_AGENT})
|
|
152
|
+
deadline = time.monotonic() + self.timeout
|
|
153
|
+
for attempt in range(2):
|
|
154
|
+
try:
|
|
155
|
+
with urllib.request.urlopen(request, timeout=max(deadline - time.monotonic(), 0.1)) as answer:
|
|
156
|
+
status, headers, raw = answer.status, answer.headers, answer.read()
|
|
157
|
+
except urllib.error.HTTPError as error:
|
|
158
|
+
status, headers = error.code, error.headers
|
|
159
|
+
try:
|
|
160
|
+
raw = error.read()
|
|
161
|
+
except OSError:
|
|
162
|
+
raw = b""
|
|
163
|
+
finally:
|
|
164
|
+
error.close()
|
|
165
|
+
except (urllib.error.URLError, OSError, http.client.HTTPException) as error:
|
|
166
|
+
if _timed_out(error):
|
|
167
|
+
raise DatacircleError(504, f"datacircle: no answer in {self.timeout:g} s") from error
|
|
168
|
+
raise DatacircleError(502, f"datacircle: {getattr(error, 'reason', None) or error}") from error
|
|
169
|
+
try:
|
|
170
|
+
raw = _unpacked(raw, headers.get("Content-Encoding"))
|
|
171
|
+
except (OSError, EOFError) as error:
|
|
172
|
+
raise DatacircleError(502, "datacircle: an answer that won't unpack", status) from error
|
|
173
|
+
if status != 429 or attempt == 1:
|
|
174
|
+
break
|
|
175
|
+
try:
|
|
176
|
+
wait = int(headers.get("Retry-After", ""))
|
|
177
|
+
except ValueError:
|
|
178
|
+
wait = 60
|
|
179
|
+
wait = wait if 1 <= wait <= 60 else 60
|
|
180
|
+
if time.monotonic() + wait >= deadline:
|
|
181
|
+
break
|
|
182
|
+
time.sleep(wait)
|
|
183
|
+
try:
|
|
184
|
+
body = json.loads(raw)
|
|
185
|
+
except ValueError:
|
|
186
|
+
body = None
|
|
187
|
+
if 400 <= status < 500:
|
|
188
|
+
words = body.get("error") if isinstance(body, dict) else None
|
|
189
|
+
raise DatacircleError(status, words if isinstance(words, str) and words else f"datacircle: {status}", status,
|
|
190
|
+
body if isinstance(body, dict) else None,
|
|
191
|
+
headers.get("Retry-After") if status == 429 else None)
|
|
192
|
+
if status != 200 or body is None:
|
|
193
|
+
raise DatacircleError(502, f"datacircle: {status}", status)
|
|
194
|
+
return raw
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""The Flask extension: Datacircle(app), or datacircle = Datacircle() then datacircle.init_app(app) in an app factory.
|
|
2
|
+
|
|
3
|
+
Its settings, read by init_app from app.config: DATACIRCLE_TIMEOUT (30, seconds to wait for the API) and
|
|
4
|
+
DATACIRCLE_CACHE_TIMEOUT (3600, seconds an answer is kept; 0 for none). It adds Jinja globals and a filter:
|
|
5
|
+
|
|
6
|
+
{{ datacircle_best_plans("email-finder", limit=3) }} a table of one API's best plans
|
|
7
|
+
{% set best = datacircle_best("email-finder", limit=3) %} the API's answer, for markup of your own
|
|
8
|
+
{{ datacircle_credit() }} a line linking https://datacircle.dev
|
|
9
|
+
{{ plan.perThousand|datacircle_dollars }} a price per 1,000 in dollars
|
|
10
|
+
|
|
11
|
+
The data is under CC BY 4.0: keep a link to datacircle.dev near it on your page. A call that fails renders nothing and is
|
|
12
|
+
logged on the "flask_datacircle" logger."""
|
|
13
|
+
|
|
14
|
+
import weakref
|
|
15
|
+
from decimal import Decimal
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Optional
|
|
18
|
+
|
|
19
|
+
from flask import Flask, current_app
|
|
20
|
+
from jinja2 import Environment, Template, TemplateNotFound
|
|
21
|
+
from markupsafe import Markup
|
|
22
|
+
|
|
23
|
+
from .client import BASE_URL, DatacircleClient, DatacircleError, logger
|
|
24
|
+
|
|
25
|
+
HOME = "https://datacircle.dev"
|
|
26
|
+
TABLE = "flask_datacircle/best_plans.html"
|
|
27
|
+
_tables: "weakref.WeakKeyDictionary[Environment, Template]" = weakref.WeakKeyDictionary()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _client_for(app: Flask, cache: Any = "memory") -> DatacircleClient:
|
|
31
|
+
app.config.setdefault("DATACIRCLE_TIMEOUT", 30)
|
|
32
|
+
app.config.setdefault("DATACIRCLE_CACHE_TIMEOUT", 3600)
|
|
33
|
+
return DatacircleClient(base_url=app.config.get("DATACIRCLE_BASE_URL") or BASE_URL,
|
|
34
|
+
timeout=app.config["DATACIRCLE_TIMEOUT"], cache=cache,
|
|
35
|
+
cache_timeout=app.config["DATACIRCLE_CACHE_TIMEOUT"])
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def get_client(app: Optional[Flask] = None) -> DatacircleClient:
|
|
39
|
+
"""The client of app, or of the current app: the one Datacircle(app) made, else one made once from app.config."""
|
|
40
|
+
app = app or current_app._get_current_object() # type: ignore[attr-defined]
|
|
41
|
+
client = app.extensions.get("datacircle")
|
|
42
|
+
if client is None:
|
|
43
|
+
client = app.extensions.setdefault("datacircle", _client_for(app))
|
|
44
|
+
return client
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Datacircle:
|
|
48
|
+
"""Datacircle's open API in a Flask app. No key.
|
|
49
|
+
|
|
50
|
+
cache: where answers are kept, an in-process MemoryCache for each app when left out, None for no cache, or any object
|
|
51
|
+
with get(key) and set(key, value, timeout), like Flask-Caching's Cache. Each method calls the current app's client."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, app: Optional[Flask] = None, *, cache: Any = "memory") -> None:
|
|
54
|
+
self.cache = cache
|
|
55
|
+
if app is not None:
|
|
56
|
+
self.init_app(app)
|
|
57
|
+
|
|
58
|
+
def init_app(self, app: Flask) -> None:
|
|
59
|
+
app.extensions["datacircle"] = _client_for(app, self.cache)
|
|
60
|
+
app.add_template_global(best, "datacircle_best")
|
|
61
|
+
app.add_template_global(best_plans, "datacircle_best_plans")
|
|
62
|
+
app.add_template_global(credit, "datacircle_credit")
|
|
63
|
+
app.add_template_filter(dollars, "datacircle_dollars")
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def client(self) -> DatacircleClient:
|
|
67
|
+
"""The current app's client."""
|
|
68
|
+
return get_client()
|
|
69
|
+
|
|
70
|
+
def list_apis(self) -> list:
|
|
71
|
+
"""GET /apis: every API on the sheet, in its order, with its slug, its counts and its best plan."""
|
|
72
|
+
return get_client().list_apis()
|
|
73
|
+
|
|
74
|
+
def best_plans(self, slug: str, *, limit: Optional[int] = None) -> dict:
|
|
75
|
+
"""GET /apis/{slug}/best: the API's plans, best first by score, each with its rank. limit: 1 to 50, 10 when None."""
|
|
76
|
+
return get_client().best_plans(slug, limit=limit)
|
|
77
|
+
|
|
78
|
+
def search_plans(self, *, api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
|
|
79
|
+
limit: Optional[int] = None, offset: Optional[int] = None) -> dict:
|
|
80
|
+
"""GET /plans: every plan, or an API's, or those whose provider or plan name holds every word of query.
|
|
81
|
+
sort: score (the default), provider or price. limit: 1 to 50, 10 when None."""
|
|
82
|
+
return get_client().search_plans(api=api, query=query, sort=sort, limit=limit, offset=offset)
|
|
83
|
+
|
|
84
|
+
def provider(self, slug: str, *, plans: Optional[str] = None) -> dict:
|
|
85
|
+
"""GET /providers/{slug}: one provider on each API it sells, with its rank there. plans: all (the default),
|
|
86
|
+
best (its best plan on each API alone) or none (the ranks alone): a big provider's every plan is megabytes."""
|
|
87
|
+
return get_client().provider(slug, plans=plans)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def best(slug: str, limit: Optional[int] = None) -> Optional[dict]:
|
|
91
|
+
"""The answer of GET /apis/{slug}/best: {"api", "bestPage", "plans": [{"rank", "provider", "plan", "score",
|
|
92
|
+
"perThousand", "page", ...}]}, None when the call failed."""
|
|
93
|
+
try:
|
|
94
|
+
return get_client().best_plans(str(slug), limit=limit)
|
|
95
|
+
except DatacircleError as error:
|
|
96
|
+
logger.warning("datacircle: the best plans of %r: %s", slug, error)
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def best_plans(slug: str, limit: Optional[int] = None, css_class: str = "") -> Markup:
|
|
101
|
+
"""A table of one API's best plans, best first: rank, provider (a link to the plan's page on datacircle.dev), plan,
|
|
102
|
+
score out of 100 and $ per 1,000. Its caption links the API's page of best plans. Nothing when the call failed.
|
|
103
|
+
Its template is flask_datacircle/best_plans.html: one of that name in your templates folder is used instead."""
|
|
104
|
+
found = best(slug, limit)
|
|
105
|
+
if not found:
|
|
106
|
+
return Markup("")
|
|
107
|
+
env = current_app.jinja_env
|
|
108
|
+
try:
|
|
109
|
+
table = env.get_template(TABLE)
|
|
110
|
+
except TemplateNotFound:
|
|
111
|
+
table = _tables.get(env)
|
|
112
|
+
if table is None:
|
|
113
|
+
table = _tables[env] = env.from_string((Path(__file__).parent / "templates" / TABLE).read_text("utf-8"))
|
|
114
|
+
return Markup(table.render(best=found, css_class=css_class,
|
|
115
|
+
link=found.get("bestPage") or found.get("sheetPage") or HOME))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def credit(href: str = HOME, css_class: str = "") -> Markup:
|
|
119
|
+
"""A line crediting Datacircle, "Scores and prices from Datacircle.", linking https://datacircle.dev or href."""
|
|
120
|
+
classes = "datacircle-credit" + (f" {css_class}" if css_class else "")
|
|
121
|
+
return Markup('<p class="{}">Scores and prices from <a href="{}">Datacircle</a>.</p>').format(classes, href or HOME)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def dollars(value: Any) -> str:
|
|
125
|
+
"""A price per 1,000 in dollars: $7.98, $1,250.00, two digits kept below $0.10 as $0.017, a dash for none."""
|
|
126
|
+
if value is None or value == "":
|
|
127
|
+
return "–"
|
|
128
|
+
try:
|
|
129
|
+
number = Decimal(str(value))
|
|
130
|
+
except ArithmeticError:
|
|
131
|
+
return "–"
|
|
132
|
+
if not number.is_finite():
|
|
133
|
+
return "–"
|
|
134
|
+
if 0 < number < Decimal("0.1"):
|
|
135
|
+
return f"${number:.{1 - number.adjusted()}f}"
|
|
136
|
+
return f"${number:,.2f}"
|
|
137
|
+
|
|
File without changes
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
<table class="datacircle datacircle-best{% if css_class %} {{ css_class }}{% endif %}">
|
|
2
|
+
<caption>The best {{ best.api }} APIs. Scores and prices from <a href="{{ link }}">Datacircle</a>.</caption>
|
|
3
|
+
<thead>
|
|
4
|
+
<tr><th scope="col">Rank</th><th scope="col">Provider</th><th scope="col">Plan</th><th scope="col">Score</th><th scope="col">$ per 1,000</th></tr>
|
|
5
|
+
</thead>
|
|
6
|
+
<tbody>
|
|
7
|
+
{% for plan in best.plans %} <tr><td>{{ "–" if plan.rank is none else plan.rank }}</td><td>{% if plan.page %}<a href="{{ plan.page }}">{{ plan.provider }}</a>{% else %}{{ plan.provider }}{% endif %}</td><td>{{ plan.plan }}</td><td>{{ "–" if plan.score is none else plan.score }}</td><td>{{ plan.perThousand|datacircle_dollars }}</td></tr>
|
|
8
|
+
{% endfor %} </tbody>
|
|
9
|
+
</table>
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: flask-datacircle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Datacircle's open API in a Flask app: find the best go-to-market (GTM) APIs
|
|
5
|
+
Project-URL: Homepage, https://datacircle.dev
|
|
6
|
+
Project-URL: Documentation, https://api.datacircle.dev/v1/openapi.json
|
|
7
|
+
Project-URL: Repository, https://github.com/waynehamadi/flask-datacircle
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: api,api-client,api-pricing,b2b-data,datacircle,flask,flask-extension,gtm
|
|
11
|
+
Classifier: Framework :: Flask
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
15
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Requires-Dist: flask>=2.3
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# flask-datacircle
|
|
22
|
+
|
|
23
|
+
Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website. GTM means go-to-market. GTM APIs are the APIs sales and marketing teams use.
|
|
24
|
+
|
|
25
|
+
Our website: https://datacircle.dev
|
|
26
|
+
|
|
27
|
+
With this package, a Flask app calls the public Datacircle API at https://api.datacircle.dev/v1. You need no key and no account.
|
|
28
|
+
|
|
29
|
+
| Method | What the method gives | Call |
|
|
30
|
+
| --- | --- | --- |
|
|
31
|
+
| `list_apis()` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
|
|
32
|
+
| `best_plans(slug, limit=)` | One API's plans, best score out of 100 first. Each plan comes with a rank and a price per 1,000 calls | `GET /apis/{slug}/best` |
|
|
33
|
+
| `search_plans(api=, query=, sort=, limit=, offset=)` | Plans that match a provider or plan name, on all APIs or on one API. You can sort them by score, provider or price | `GET /plans` |
|
|
34
|
+
| `provider(slug, plans=)` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
|
|
35
|
+
|
|
36
|
+
The package has a blueprint and Jinja helpers too. With the blueprint, you serve all four Datacircle API calls from your own app's address. The Jinja helpers show an API's best plans on your pages. The package keeps each answer in memory for an hour. The package works on Flask 2.3 or later, with Python 3.9 or later.
|
|
37
|
+
|
|
38
|
+
## Install
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install flask-datacircle
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Use the extension in a view
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from flask import Flask
|
|
48
|
+
from flask_datacircle import Datacircle
|
|
49
|
+
|
|
50
|
+
app = Flask(__name__)
|
|
51
|
+
datacircle = Datacircle(app)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@app.get("/best/<slug>")
|
|
55
|
+
def best(slug):
|
|
56
|
+
return datacircle.best_plans(slug, limit=3)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`GET /best/email-finder` on this app returns the three best plans to find a person's work email.
|
|
60
|
+
|
|
61
|
+
With an app factory, make the extension first and call `init_app`:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from flask import Flask
|
|
65
|
+
from flask_datacircle import Datacircle
|
|
66
|
+
|
|
67
|
+
datacircle = Datacircle()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def create_app():
|
|
71
|
+
app = Flask(__name__)
|
|
72
|
+
datacircle.init_app(app)
|
|
73
|
+
|
|
74
|
+
@app.get("/apis")
|
|
75
|
+
def apis():
|
|
76
|
+
return {"apis": datacircle.list_apis()}
|
|
77
|
+
|
|
78
|
+
return app
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Register the blueprint
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from flask import Flask
|
|
85
|
+
from flask_datacircle import Datacircle, datacircle_blueprint
|
|
86
|
+
|
|
87
|
+
app = Flask(__name__)
|
|
88
|
+
Datacircle(app)
|
|
89
|
+
app.register_blueprint(datacircle_blueprint, url_prefix="/datacircle")
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
| Path on your app | Datacircle API call |
|
|
93
|
+
| --- | --- |
|
|
94
|
+
| `GET /datacircle/apis` | `GET /apis` |
|
|
95
|
+
| `GET /datacircle/apis/{slug}/best?limit=3` | `GET /apis/{slug}/best` |
|
|
96
|
+
| `GET /datacircle/plans?api=&query=&sort=&limit=&offset=` | `GET /plans` |
|
|
97
|
+
| `GET /datacircle/providers/{slug}?plans=best` | `GET /providers/{slug}` |
|
|
98
|
+
|
|
99
|
+
Your app passes on the Datacircle API's own query parameters. Your app drops any other query parameters. Your app returns the Datacircle API's JSON unchanged. Use these endpoint names with `url_for`: `datacircle.apis`, `datacircle.best`, `datacircle.plans` and `datacircle.provider`.
|
|
100
|
+
|
|
101
|
+
## Show an API's best plans on a page
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from flask import Flask, render_template_string
|
|
105
|
+
from flask_datacircle import Datacircle
|
|
106
|
+
|
|
107
|
+
app = Flask(__name__)
|
|
108
|
+
Datacircle(app)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@app.get("/")
|
|
112
|
+
def home():
|
|
113
|
+
return render_template_string('{{ datacircle_best_plans("email-finder", limit=3) }}')
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
`datacircle_best_plans` shows a table of the three best plans to find a person's work email. Each row has a rank, a provider, a plan, a score out of 100 and a price per 1,000 emails. Each provider links to the plan's page on datacircle.dev. The table's caption links to Datacircle.
|
|
117
|
+
|
|
118
|
+
To write your own HTML, put the plans in a variable:
|
|
119
|
+
|
|
120
|
+
```jinja
|
|
121
|
+
{% set best = datacircle_best("email-finder", limit=3) %}
|
|
122
|
+
<ul>
|
|
123
|
+
{% for plan in best.plans %}
|
|
124
|
+
<li>{{ plan.provider }}, {{ plan.plan }}: {{ plan.perThousand|datacircle_dollars }} per 1,000</li>
|
|
125
|
+
{% endfor %}
|
|
126
|
+
</ul>
|
|
127
|
+
{{ datacircle_credit() }}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
`datacircle_credit()` adds a line with a link to https://datacircle.dev: "Scores and prices from Datacircle." Our data is under CC BY 4.0. Keep a link to datacircle.dev near our data on your page.
|
|
131
|
+
|
|
132
|
+
After a failed call to Datacircle, `datacircle_best_plans` shows nothing. After a failed call, `datacircle_best` gives `None`. `datacircle_best_plans` and `datacircle_best` log the error to the `flask_datacircle` logger. To change the table, copy `flask_datacircle/best_plans.html` from the package into your own templates folder.
|
|
133
|
+
|
|
134
|
+
## Errors
|
|
135
|
+
|
|
136
|
+
A call that fails raises a `DatacircleError`. The blueprint returns the API's status and the API's message, like a 404 and `{"error": "no API has the slug bright-data", "slugs": [...]}`.
|
|
137
|
+
|
|
138
|
+
| Case | Status |
|
|
139
|
+
| --- | --- |
|
|
140
|
+
| The API refuses the call, like an unknown slug or a limit over 50 | The API's own 400 or 404 |
|
|
141
|
+
| More than 60 calls in a minute from your server | 429, after one retry at the API's wait time |
|
|
142
|
+
| The API fails or can't be reached | 502 |
|
|
143
|
+
| No answer within the timeout | 504 |
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
from flask import Flask
|
|
147
|
+
from flask_datacircle import Datacircle, DatacircleError
|
|
148
|
+
|
|
149
|
+
app = Flask(__name__)
|
|
150
|
+
datacircle = Datacircle(app)
|
|
151
|
+
|
|
152
|
+
with app.app_context():
|
|
153
|
+
try:
|
|
154
|
+
datacircle.best_plans("bright-data")
|
|
155
|
+
except DatacircleError as error:
|
|
156
|
+
print(error.status, error.message)
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
`error.status` is the HTTP status: 400, 404, 429, 502 or 504. `error.message` is the API's message. `error.body` is the API's answer. On an unknown slug, `error.body` holds the list of every API slug. On a 429, `error.retry_after` holds the API's wait in seconds.
|
|
160
|
+
|
|
161
|
+
## Settings
|
|
162
|
+
|
|
163
|
+
Both settings are optional. Defaults:
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
DATACIRCLE_TIMEOUT = 30
|
|
167
|
+
DATACIRCLE_CACHE_TIMEOUT = 3600
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
`DATACIRCLE_TIMEOUT` is the wait for the API in seconds. `DATACIRCLE_TIMEOUT` covers the wait after a 429 too. `DATACIRCLE_CACHE_TIMEOUT` sets the seconds the package keeps each answer. Set `DATACIRCLE_CACHE_TIMEOUT` to `0` to call the API each time.
|
|
171
|
+
|
|
172
|
+
The package keeps answers in the memory of each process. To keep answers in your own cache, pass your cache: `Datacircle(app, cache=cache)`. The cache can be a Flask-Caching `Cache`, or any object with `get(key)` and `set(key, value, timeout)`. Pass `cache=None` for no cache.
|
|
173
|
+
|
|
174
|
+
## Ask for less
|
|
175
|
+
|
|
176
|
+
`provider(slug)` gives every plan of the provider on each API. For a big provider, the answer is many megabytes. Pass `plans="best"` to get the provider's best plan on each API. Pass `plans="none"` to get the ranks alone. On the blueprint's `GET /datacircle/providers/{slug}`, add `?plans=best` or `?plans=none`.
|
|
177
|
+
|
|
178
|
+
## Links
|
|
179
|
+
|
|
180
|
+
- Datacircle: https://datacircle.dev
|
|
181
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
182
|
+
- The meaning of each key in a plan: https://datacircle.dev/fields
|
|
183
|
+
|
|
184
|
+
## License
|
|
185
|
+
|
|
186
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
flask_datacircle/__init__.py,sha256=jni5xRSEijc6PbfmU91U2O30rwhjqZBXphx7K-wk8fA,476
|
|
2
|
+
flask_datacircle/blueprint.py,sha256=xTGD1gxntcvrCAkeEsTxXjzVnTiUxAQOmhptZjVieYg,1934
|
|
3
|
+
flask_datacircle/client.py,sha256=lEcQO911Qn9K9WCSVjk-ILDaTH3AO5SY81ptaMv0M8w,9345
|
|
4
|
+
flask_datacircle/extension.py,sha256=D98q3V07eZES9XjIqg7jfPN3LYeH-McOLSd8mZphM_4,6779
|
|
5
|
+
flask_datacircle/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
flask_datacircle/templates/flask_datacircle/best_plans.html,sha256=u7QcWMzBiLfrZ2L-kfEo9NgA02t7LYclrmeSv9Rm2P4,759
|
|
7
|
+
flask_datacircle-0.1.0.dist-info/METADATA,sha256=EqVpuBymGAz17hQtG9ge9fLANTtSr8XnUiTOhtmRqLU,7437
|
|
8
|
+
flask_datacircle-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
flask_datacircle-0.1.0.dist-info/licenses/LICENSE,sha256=dpgF7zGxeOd9IpQ9yUGa4a-cTj8fI6ulHnuilZEonCo,1067
|
|
10
|
+
flask_datacircle-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Datacircle
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|