flask-datacircle 0.1.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.
@@ -0,0 +1,5 @@
1
+ dist/
2
+ __pycache__/
3
+ *.pyc
4
+ .venv/
5
+ .pytest_cache/
@@ -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.
@@ -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,166 @@
1
+ # flask-datacircle
2
+
3
+ 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.
4
+
5
+ Our website: https://datacircle.dev
6
+
7
+ With this package, a Flask app calls the public Datacircle API at https://api.datacircle.dev/v1. You need no key and no account.
8
+
9
+ | Method | What the method gives | Call |
10
+ | --- | --- | --- |
11
+ | `list_apis()` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
12
+ | `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` |
13
+ | `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` |
14
+ | `provider(slug, plans=)` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
15
+
16
+ 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.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pip install flask-datacircle
22
+ ```
23
+
24
+ ## Use the extension in a view
25
+
26
+ ```python
27
+ from flask import Flask
28
+ from flask_datacircle import Datacircle
29
+
30
+ app = Flask(__name__)
31
+ datacircle = Datacircle(app)
32
+
33
+
34
+ @app.get("/best/<slug>")
35
+ def best(slug):
36
+ return datacircle.best_plans(slug, limit=3)
37
+ ```
38
+
39
+ `GET /best/email-finder` on this app returns the three best plans to find a person's work email.
40
+
41
+ With an app factory, make the extension first and call `init_app`:
42
+
43
+ ```python
44
+ from flask import Flask
45
+ from flask_datacircle import Datacircle
46
+
47
+ datacircle = Datacircle()
48
+
49
+
50
+ def create_app():
51
+ app = Flask(__name__)
52
+ datacircle.init_app(app)
53
+
54
+ @app.get("/apis")
55
+ def apis():
56
+ return {"apis": datacircle.list_apis()}
57
+
58
+ return app
59
+ ```
60
+
61
+ ## Register the blueprint
62
+
63
+ ```python
64
+ from flask import Flask
65
+ from flask_datacircle import Datacircle, datacircle_blueprint
66
+
67
+ app = Flask(__name__)
68
+ Datacircle(app)
69
+ app.register_blueprint(datacircle_blueprint, url_prefix="/datacircle")
70
+ ```
71
+
72
+ | Path on your app | Datacircle API call |
73
+ | --- | --- |
74
+ | `GET /datacircle/apis` | `GET /apis` |
75
+ | `GET /datacircle/apis/{slug}/best?limit=3` | `GET /apis/{slug}/best` |
76
+ | `GET /datacircle/plans?api=&query=&sort=&limit=&offset=` | `GET /plans` |
77
+ | `GET /datacircle/providers/{slug}?plans=best` | `GET /providers/{slug}` |
78
+
79
+ 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`.
80
+
81
+ ## Show an API's best plans on a page
82
+
83
+ ```python
84
+ from flask import Flask, render_template_string
85
+ from flask_datacircle import Datacircle
86
+
87
+ app = Flask(__name__)
88
+ Datacircle(app)
89
+
90
+
91
+ @app.get("/")
92
+ def home():
93
+ return render_template_string('{{ datacircle_best_plans("email-finder", limit=3) }}')
94
+ ```
95
+
96
+ `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.
97
+
98
+ To write your own HTML, put the plans in a variable:
99
+
100
+ ```jinja
101
+ {% set best = datacircle_best("email-finder", limit=3) %}
102
+ <ul>
103
+ {% for plan in best.plans %}
104
+ <li>{{ plan.provider }}, {{ plan.plan }}: {{ plan.perThousand|datacircle_dollars }} per 1,000</li>
105
+ {% endfor %}
106
+ </ul>
107
+ {{ datacircle_credit() }}
108
+ ```
109
+
110
+ `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.
111
+
112
+ 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.
113
+
114
+ ## Errors
115
+
116
+ 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": [...]}`.
117
+
118
+ | Case | Status |
119
+ | --- | --- |
120
+ | The API refuses the call, like an unknown slug or a limit over 50 | The API's own 400 or 404 |
121
+ | More than 60 calls in a minute from your server | 429, after one retry at the API's wait time |
122
+ | The API fails or can't be reached | 502 |
123
+ | No answer within the timeout | 504 |
124
+
125
+ ```python
126
+ from flask import Flask
127
+ from flask_datacircle import Datacircle, DatacircleError
128
+
129
+ app = Flask(__name__)
130
+ datacircle = Datacircle(app)
131
+
132
+ with app.app_context():
133
+ try:
134
+ datacircle.best_plans("bright-data")
135
+ except DatacircleError as error:
136
+ print(error.status, error.message)
137
+ ```
138
+
139
+ `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.
140
+
141
+ ## Settings
142
+
143
+ Both settings are optional. Defaults:
144
+
145
+ ```python
146
+ DATACIRCLE_TIMEOUT = 30
147
+ DATACIRCLE_CACHE_TIMEOUT = 3600
148
+ ```
149
+
150
+ `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.
151
+
152
+ 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.
153
+
154
+ ## Ask for less
155
+
156
+ `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`.
157
+
158
+ ## Links
159
+
160
+ - Datacircle: https://datacircle.dev
161
+ - The API's spec: https://api.datacircle.dev/v1/openapi.json
162
+ - The meaning of each key in a plan: https://datacircle.dev/fields
163
+
164
+ ## License
165
+
166
+ MIT
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "flask-datacircle"
7
+ version = "0.1.0"
8
+ description = "Datacircle's open API in a Flask app: find the best go-to-market (GTM) APIs"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ # The client calls the API by urllib, so Flask is the only dependency.
13
+ dependencies = ["Flask>=2.3"]
14
+ keywords = ["flask", "flask-extension", "api-client", "gtm", "api", "api-pricing", "b2b-data", "datacircle"]
15
+ classifiers = [
16
+ "Framework :: Flask",
17
+ "Programming Language :: Python :: 3",
18
+ "Operating System :: OS Independent",
19
+ "Topic :: Internet :: WWW/HTTP",
20
+ "Topic :: Software Development :: Libraries",
21
+ "Typing :: Typed",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://datacircle.dev"
26
+ Documentation = "https://api.datacircle.dev/v1/openapi.json"
27
+ Repository = "https://github.com/waynehamadi/flask-datacircle"
28
+
29
+ [dependency-groups]
30
+ test = ["pytest>=8"]
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["src/flask_datacircle"]
34
+
35
+ [tool.hatch.build.targets.sdist]
36
+ include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
@@ -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,25 @@
1
+ import pytest
2
+ from flask import Flask
3
+
4
+ from flask_datacircle import Datacircle, datacircle_blueprint
5
+ from standin import StandIn
6
+
7
+
8
+ @pytest.fixture
9
+ def stand_in():
10
+ s = StandIn()
11
+ yield s
12
+ s.close()
13
+
14
+
15
+ def make_app(base_url, **config):
16
+ app = Flask(__name__)
17
+ app.config.update(DATACIRCLE_BASE_URL=base_url, **config)
18
+ Datacircle(app)
19
+ app.register_blueprint(datacircle_blueprint, url_prefix="/datacircle")
20
+ return app
21
+
22
+
23
+ @pytest.fixture
24
+ def app(stand_in):
25
+ return make_app(stand_in.url)
@@ -0,0 +1,50 @@
1
+ """A stand-in of the API on 127.0.0.1: each test sets what it answers and reads what it was asked."""
2
+ import gzip
3
+ import json
4
+ import threading
5
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
6
+
7
+
8
+ class StandIn:
9
+ def __init__(self):
10
+ self.asked = [] # (path with query, headers)
11
+ self.answers = [] # (status, body bytes or JSON, headers), one per call, the last one kept
12
+ self.delay = 0.0
13
+ stand_in = self
14
+
15
+ class Handler(BaseHTTPRequestHandler):
16
+ def do_GET(self):
17
+ stand_in.asked.append((self.path, dict(self.headers)))
18
+ status, body, headers = stand_in.answers.pop(0) if len(stand_in.answers) > 1 else stand_in.answers[0]
19
+ if stand_in.delay:
20
+ threading.Event().wait(stand_in.delay)
21
+ raw = body if isinstance(body, bytes) else json.dumps(body).encode()
22
+ self.send_response(status)
23
+ headers = dict(headers)
24
+ if "gzip" in (self.headers.get("Accept-Encoding") or "") and not headers.pop("plain", False):
25
+ raw = gzip.compress(raw)
26
+ self.send_header("Content-Encoding", "gzip")
27
+ self.send_header("Content-Type", headers.pop("Content-Type", "application/json"))
28
+ for name, value in headers.items():
29
+ self.send_header(name, value)
30
+ self.send_header("Content-Length", str(len(raw)))
31
+ self.end_headers()
32
+ try:
33
+ self.wfile.write(raw)
34
+ except OSError:
35
+ pass
36
+
37
+ def log_message(self, *args):
38
+ pass
39
+
40
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
41
+ self.server.daemon_threads = True
42
+ self.url = f"http://127.0.0.1:{self.server.server_address[1]}/v1"
43
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
44
+
45
+ def answer(self, *answers):
46
+ self.answers = [a if isinstance(a, tuple) and len(a) == 3 else (a[0], a[1], {}) for a in answers]
47
+
48
+ def close(self):
49
+ self.server.shutdown()
50
+ self.server.server_close()
@@ -0,0 +1,186 @@
1
+ """The client on a stand-in of the API: what it asks, what it unpacks, how it fails, what it keeps."""
2
+ import socket
3
+ import time
4
+
5
+ import pytest
6
+
7
+ from flask_datacircle import USER_AGENT, DatacircleClient, DatacircleError, MemoryCache
8
+
9
+ APIS = [{"api": "Employee email", "slug": "email-finder"}]
10
+
11
+
12
+ def client(stand_in, **kwargs):
13
+ return DatacircleClient(base_url=stand_in.url, cache=kwargs.pop("cache", None), **kwargs)
14
+
15
+
16
+ def test_gzip_asked_and_unpacked(stand_in):
17
+ stand_in.answer((200, APIS))
18
+ assert client(stand_in).list_apis() == APIS
19
+ path, headers = stand_in.asked[0]
20
+ assert path == "/v1/apis" and headers["Accept-Encoding"] == "gzip" and headers["User-Agent"] == USER_AGENT
21
+
22
+
23
+ def test_plain_answer(stand_in):
24
+ stand_in.answer((200, APIS, {"plain": True}))
25
+ assert client(stand_in).list_apis() == APIS
26
+
27
+
28
+ def test_parameters(stand_in):
29
+ stand_in.answer((200, {"plans": []}))
30
+ c = client(stand_in)
31
+ c.best_plans("email finder/x", limit=3)
32
+ c.search_plans(api="email-finder", query="bright data", sort="price", limit=5, offset=10)
33
+ c.search_plans(query="")
34
+ c.provider("bright-data", plans="none")
35
+ assert [p for p, _ in stand_in.asked] == [
36
+ "/v1/apis/email%20finder%2Fx/best?limit=3",
37
+ "/v1/plans?api=email-finder&query=bright+data&sort=price&limit=5&offset=10",
38
+ "/v1/plans",
39
+ "/v1/providers/bright-data?plans=none",
40
+ ]
41
+
42
+
43
+ def test_404_in_the_api_words(stand_in):
44
+ stand_in.answer((404, {"error": "no API has the slug nope", "slugs": ["email-finder"]}))
45
+ with pytest.raises(DatacircleError) as raised:
46
+ client(stand_in).best_plans("nope")
47
+ e = raised.value
48
+ assert (e.status, e.api_status, e.message, e.body["slugs"]) == (404, 404, "no API has the slug nope", ["email-finder"])
49
+
50
+
51
+ def test_400(stand_in):
52
+ stand_in.answer((400, {"error": "limit is 1 to 50"}))
53
+ with pytest.raises(DatacircleError) as raised:
54
+ client(stand_in).search_plans(limit=99)
55
+ assert raised.value.status == 400 and raised.value.message == "limit is 1 to 50"
56
+
57
+
58
+ def test_429_waited_once(stand_in):
59
+ stand_in.answer((429, {"error": "slow down"}, {"Retry-After": "1"}), (200, APIS))
60
+ started = time.monotonic()
61
+ assert client(stand_in).list_apis() == APIS
62
+ assert time.monotonic() - started >= 1 and len(stand_in.asked) == 2
63
+
64
+
65
+ def test_429_twice(stand_in):
66
+ stand_in.answer((429, {"error": "slow down"}, {"Retry-After": "1"}))
67
+ with pytest.raises(DatacircleError) as raised:
68
+ client(stand_in).list_apis()
69
+ assert raised.value.status == 429 and raised.value.retry_after == "1" and len(stand_in.asked) == 2
70
+
71
+
72
+ def test_429_past_the_timeout(stand_in):
73
+ stand_in.answer((429, {"error": "slow down"}, {"Retry-After": "30"}))
74
+ started = time.monotonic()
75
+ with pytest.raises(DatacircleError) as raised:
76
+ client(stand_in, timeout=5).list_apis()
77
+ assert raised.value.retry_after == "30" and time.monotonic() - started < 2 and len(stand_in.asked) == 1
78
+
79
+
80
+ def test_500(stand_in):
81
+ stand_in.answer((500, {"error": "down"}))
82
+ with pytest.raises(DatacircleError) as raised:
83
+ client(stand_in).list_apis()
84
+ assert raised.value.status == 502 and raised.value.api_status == 500
85
+
86
+
87
+ def test_html(stand_in):
88
+ stand_in.answer((200, b"<html>hi</html>", {"Content-Type": "text/html"}))
89
+ with pytest.raises(DatacircleError) as raised:
90
+ client(stand_in).list_apis()
91
+ assert raised.value.status == 502
92
+
93
+
94
+ def test_refused_port():
95
+ with socket.socket() as s:
96
+ s.bind(("127.0.0.1", 0))
97
+ port = s.getsockname()[1]
98
+ with pytest.raises(DatacircleError) as raised:
99
+ DatacircleClient(base_url=f"http://127.0.0.1:{port}/v1", cache=None).list_apis()
100
+ assert raised.value.status == 502 and raised.value.api_status is None
101
+
102
+
103
+ def test_timeout(stand_in):
104
+ stand_in.answer((200, APIS))
105
+ stand_in.delay = 2
106
+ with pytest.raises(DatacircleError) as raised:
107
+ client(stand_in, timeout=0.5).list_apis()
108
+ assert raised.value.status == 504
109
+
110
+
111
+ def test_memory_cache_by_default(stand_in):
112
+ stand_in.answer((200, APIS))
113
+ c = DatacircleClient(base_url=stand_in.url)
114
+ assert isinstance(c.cache, MemoryCache)
115
+ assert c.list_apis() == c.list_apis() == APIS and len(stand_in.asked) == 1
116
+ c.best_plans("email-finder", limit=2)
117
+ assert len(stand_in.asked) == 2
118
+
119
+
120
+ def test_refusals_not_kept(stand_in):
121
+ stand_in.answer((404, {"error": "no"}), (200, APIS))
122
+ c = DatacircleClient(base_url=stand_in.url)
123
+ with pytest.raises(DatacircleError):
124
+ c.list_apis()
125
+ assert c.list_apis() == APIS and len(stand_in.asked) == 2
126
+
127
+
128
+ def test_no_cache(stand_in):
129
+ stand_in.answer((200, APIS))
130
+ c = client(stand_in)
131
+ c.list_apis()
132
+ c.list_apis()
133
+ assert len(stand_in.asked) == 2
134
+
135
+
136
+ def test_cache_timeout_zero_keeps_nothing(stand_in):
137
+ stand_in.answer((200, APIS))
138
+ c = DatacircleClient(base_url=stand_in.url, cache_timeout=0)
139
+ c.list_apis()
140
+ c.list_apis()
141
+ assert len(stand_in.asked) == 2
142
+
143
+
144
+ def test_a_cache_of_your_own(stand_in):
145
+ class Kept:
146
+ def __init__(self):
147
+ self.kept, self.timeouts = {}, []
148
+
149
+ def get(self, key):
150
+ return self.kept.get(key)
151
+
152
+ def set(self, key, value, timeout=None):
153
+ self.kept[key] = value
154
+ self.timeouts.append(timeout)
155
+
156
+ stand_in.answer((200, APIS))
157
+ kept = Kept()
158
+ c = DatacircleClient(base_url=stand_in.url, cache=kept, cache_timeout=60)
159
+ c.list_apis()
160
+ c.list_apis()
161
+ assert len(stand_in.asked) == 1 and kept.timeouts == [60]
162
+
163
+
164
+ def test_a_cache_down_never_stops_a_call(stand_in):
165
+ class Down:
166
+ def get(self, key):
167
+ raise ConnectionError("down")
168
+
169
+ def set(self, key, value, timeout=None):
170
+ raise ConnectionError("down")
171
+
172
+ stand_in.answer((200, APIS))
173
+ assert DatacircleClient(base_url=stand_in.url, cache=Down()).list_apis() == APIS
174
+
175
+
176
+ def test_memory_cache_bounds():
177
+ cache = MemoryCache(max_bytes=10)
178
+ cache.set("a", b"12345")
179
+ cache.set("b", b"12345")
180
+ cache.set("c", b"123")
181
+ assert cache.get("a") is None and cache.get("b") == b"12345" and cache.get("c") == b"123"
182
+ cache.set("big", b"x" * 11)
183
+ assert cache.get("big") is None
184
+ cache.set("d", b"1", timeout=1)
185
+ time.sleep(1.1)
186
+ assert cache.get("d") is None
@@ -0,0 +1,174 @@
1
+ """The extension, the blueprint and the Jinja helpers in a Flask app, on a stand-in of the API."""
2
+ import logging
3
+
4
+ import pytest
5
+ from flask import Flask, render_template_string, url_for
6
+ from jinja2 import DictLoader
7
+
8
+ from conftest import make_app
9
+ from flask_datacircle import Datacircle, DatacircleClient, DatacircleError, datacircle_blueprint, get_client
10
+
11
+ BEST = {"api": "Employee email", "slug": "email-finder", "bestPage": "https://datacircle.dev/best-email-finder-api",
12
+ "plans": [{"rank": 1, "provider": "GetProspect", "plan": "Growth 50k", "score": 84, "perThousand": 7.98,
13
+ "page": "https://datacircle.dev/find-email-apis/getprospect/x"},
14
+ {"rank": None, "provider": "<b>Bad</b>", "plan": "A & B", "score": None, "perThousand": 0.0174, "page": None}]}
15
+
16
+
17
+ def test_extension_gives_the_app_a_client(app, stand_in):
18
+ client = app.extensions["datacircle"]
19
+ assert isinstance(client, DatacircleClient) and client.base_url == stand_in.url and client.timeout == 30
20
+ assert app.config["DATACIRCLE_TIMEOUT"] == 30 and app.config["DATACIRCLE_CACHE_TIMEOUT"] == 3600
21
+ with app.app_context():
22
+ assert get_client() is client
23
+
24
+
25
+ def test_config_read(stand_in):
26
+ app = make_app(stand_in.url, DATACIRCLE_TIMEOUT=5, DATACIRCLE_CACHE_TIMEOUT=0)
27
+ assert app.extensions["datacircle"].timeout == 5 and app.extensions["datacircle"].cache_timeout == 0
28
+
29
+
30
+ def test_init_app_in_a_factory_one_client_each(stand_in):
31
+ datacircle = Datacircle()
32
+ apps = []
33
+ for _ in range(2):
34
+ app = Flask(__name__)
35
+ app.config["DATACIRCLE_BASE_URL"] = stand_in.url
36
+ datacircle.init_app(app)
37
+ apps.append(app)
38
+ assert apps[0].extensions["datacircle"] is not apps[1].extensions["datacircle"]
39
+ stand_in.answer((200, BEST))
40
+ for app in apps:
41
+ with app.app_context():
42
+ assert datacircle.best_plans("email-finder", limit=2) == BEST
43
+ assert datacircle.client is app.extensions["datacircle"]
44
+ assert len(stand_in.asked) == 2
45
+
46
+
47
+ def test_methods_call_the_current_app(app, stand_in):
48
+ stand_in.answer((200, {"plans": []}))
49
+ datacircle = Datacircle()
50
+ with app.app_context():
51
+ datacircle.list_apis()
52
+ datacircle.best_plans("email-finder", limit=3)
53
+ datacircle.search_plans(api="email-finder", sort="price", limit=2)
54
+ datacircle.provider("bright-data", plans="best")
55
+ assert [p for p, _ in stand_in.asked] == ["/v1/apis", "/v1/apis/email-finder/best?limit=3",
56
+ "/v1/plans?api=email-finder&sort=price&limit=2",
57
+ "/v1/providers/bright-data?plans=best"]
58
+
59
+
60
+ def test_a_cache_of_your_own_or_none(stand_in):
61
+ app = Flask(__name__)
62
+ app.config["DATACIRCLE_BASE_URL"] = stand_in.url
63
+ Datacircle(app, cache=None)
64
+ stand_in.answer((200, BEST))
65
+ with app.app_context():
66
+ get_client().best_plans("email-finder")
67
+ get_client().best_plans("email-finder")
68
+ assert len(stand_in.asked) == 2
69
+
70
+
71
+ def test_blueprint_without_the_extension(stand_in):
72
+ app = Flask(__name__)
73
+ app.config["DATACIRCLE_BASE_URL"] = stand_in.url
74
+ app.register_blueprint(datacircle_blueprint, url_prefix="/dc")
75
+ stand_in.answer((200, [{"slug": "email-finder"}]))
76
+ answer = app.test_client().get("/dc/apis")
77
+ assert answer.status_code == 200 and answer.get_json() == [{"slug": "email-finder"}]
78
+
79
+
80
+ def test_blueprint_paths_and_parameters(app, stand_in):
81
+ stand_in.answer((200, {"ok": 1}, {"plain": True}))
82
+ web = app.test_client()
83
+ for path in ["/datacircle/apis", "/datacircle/apis/email-finder/best?limit=3&x=1",
84
+ "/datacircle/plans?api=email-finder&query=bright+data&sort=price&limit=5&offset=5&key=k",
85
+ "/datacircle/providers/bright-data?plans=none&y=2"]:
86
+ answer = web.get(path)
87
+ assert answer.status_code == 200 and answer.mimetype == "application/json" and answer.data == b'{"ok": 1}'
88
+ assert [p for p, _ in stand_in.asked] == ["/v1/apis", "/v1/apis/email-finder/best?limit=3",
89
+ "/v1/plans?api=email-finder&query=bright+data&sort=price&limit=5&offset=5",
90
+ "/v1/providers/bright-data?plans=none"]
91
+
92
+
93
+ def test_blueprint_refusals(app, stand_in):
94
+ web = app.test_client()
95
+ stand_in.answer((404, {"error": "no API has the slug nope", "slugs": ["email-finder"]}))
96
+ answer = web.get("/datacircle/apis/nope/best")
97
+ assert answer.status_code == 404 and answer.get_json() == {"error": "no API has the slug nope", "slugs": ["email-finder"]}
98
+ stand_in.answer((429, {"error": "slow down"}, {"Retry-After": "30"}))
99
+ answer = web.get("/datacircle/plans")
100
+ assert answer.status_code == 429 and answer.headers["Retry-After"] == "30"
101
+ stand_in.answer((500, b"oops", {"Content-Type": "text/plain"}))
102
+ answer = web.get("/datacircle/providers/x")
103
+ assert answer.status_code == 502 and answer.get_json() == {"error": "datacircle: 500"}
104
+
105
+
106
+ def test_blueprint_methods_and_names(app):
107
+ web = app.test_client()
108
+ assert web.post("/datacircle/apis").status_code == 405
109
+ with app.test_request_context():
110
+ assert url_for("datacircle.apis") == "/datacircle/apis"
111
+ assert url_for("datacircle.best", slug="email-finder", limit=3) == "/datacircle/apis/email-finder/best?limit=3"
112
+ assert url_for("datacircle.plans") == "/datacircle/plans"
113
+ assert url_for("datacircle.provider", slug="bright-data") == "/datacircle/providers/bright-data"
114
+
115
+
116
+ def test_jinja_table_escaped_and_credit(app, stand_in):
117
+ stand_in.answer((200, BEST))
118
+ with app.test_request_context():
119
+ html = render_template_string('{{ datacircle_best_plans("email-finder", limit=2, css_class="wide") }}'
120
+ '{{ datacircle_credit() }}')
121
+ assert '<table class="datacircle datacircle-best wide">' in html
122
+ assert 'Scores and prices from <a href="https://datacircle.dev/best-email-finder-api">Datacircle</a>' in html
123
+ assert '<td>1</td><td><a href="https://datacircle.dev/find-email-apis/getprospect/x">GetProspect</a></td>' in html
124
+ assert "<td>$7.98</td>" in html and "<td>$0.017</td>" in html
125
+ assert "&lt;b&gt;Bad&lt;/b&gt;" in html and "A &amp; B" in html and "<td>–</td>" in html
126
+ assert html.count("<tr><td>") == 2
127
+ assert html.endswith('<p class="datacircle-credit">Scores and prices from <a href="https://datacircle.dev">Datacircle</a>.</p>')
128
+ assert stand_in.asked[0][0] == "/v1/apis/email-finder/best?limit=2"
129
+
130
+
131
+ def test_jinja_failed_call_renders_nothing(app, stand_in, caplog):
132
+ stand_in.answer((404, {"error": "no API has the slug nope"}))
133
+ with app.test_request_context(), caplog.at_level(logging.WARNING, "flask_datacircle"):
134
+ html = render_template_string('[{{ datacircle_best_plans("nope") }}]{% set b = datacircle_best("nope") %}{{ b }}')
135
+ assert html == "[]None" and "no API has the slug nope" in caplog.text
136
+
137
+
138
+ def test_jinja_best_for_markup_of_your_own(app, stand_in):
139
+ stand_in.answer((200, BEST))
140
+ with app.test_request_context():
141
+ html = render_template_string('{% set best = datacircle_best("email-finder", limit=2) %}'
142
+ '{% for p in best.plans %}{{ p.provider }}:{{ p.perThousand|datacircle_dollars }};{% endfor %}'
143
+ '{{ datacircle_credit("https://datacircle.dev/x", css_class="small") }}')
144
+ assert html.startswith("GetProspect:$7.98;&lt;b&gt;Bad&lt;/b&gt;:$0.017;")
145
+ assert '<p class="datacircle-credit small">' in html and 'href="https://datacircle.dev/x"' in html
146
+
147
+
148
+ def test_jinja_table_template_of_your_own(stand_in):
149
+ app = make_app(stand_in.url)
150
+ app.jinja_loader = DictLoader({"flask_datacircle/best_plans.html": "mine: {{ best.plans|length }} {{ link }}"})
151
+ stand_in.answer((200, BEST))
152
+ with app.test_request_context():
153
+ assert render_template_string('{{ datacircle_best_plans("email-finder") }}') == \
154
+ "mine: 2 https://datacircle.dev/best-email-finder-api"
155
+
156
+
157
+ @pytest.mark.parametrize("value,shown", [(7.98, "$7.98"), (1250, "$1,250.00"), (0.0174, "$0.017"), (0.1497, "$0.15"),
158
+ (0, "$0.00"), (None, "–"), ("", "–"), ("x", "–"), (float("nan"), "–")])
159
+ def test_dollars(app, value, shown):
160
+ with app.app_context():
161
+ assert app.jinja_env.filters["datacircle_dollars"](value) == shown
162
+
163
+
164
+ def test_errors_raised_in_a_view(app, stand_in):
165
+ @app.get("/mine")
166
+ def mine():
167
+ try:
168
+ return get_client().best_plans("nope")
169
+ except DatacircleError as error:
170
+ return {"status": error.status, "message": error.message}, error.status
171
+
172
+ stand_in.answer((404, {"error": "no API has the slug nope"}))
173
+ answer = app.test_client().get("/mine")
174
+ assert answer.status_code == 404 and answer.get_json() == {"status": 404, "message": "no API has the slug nope"}
@@ -0,0 +1,61 @@
1
+ """On the live API, with DATACIRCLE_LIVE=1: each call through the client, the extension, the blueprint and Jinja."""
2
+ import os
3
+
4
+ import pytest
5
+ from flask import Flask, render_template_string
6
+
7
+ from flask_datacircle import BASE_URL, Datacircle, DatacircleClient, DatacircleError, datacircle_blueprint
8
+
9
+ pytestmark = pytest.mark.skipif(os.environ.get("DATACIRCLE_LIVE") != "1", reason="DATACIRCLE_LIVE=1 calls the live API")
10
+
11
+
12
+ @pytest.fixture
13
+ def app():
14
+ app = Flask(__name__)
15
+ datacircle = Datacircle(app)
16
+ app.register_blueprint(datacircle_blueprint, url_prefix="/datacircle")
17
+ app.config["datacircle"] = datacircle
18
+ return app
19
+
20
+
21
+ def test_client_live():
22
+ c = DatacircleClient(cache=None)
23
+ assert c.base_url == BASE_URL
24
+ apis = c.list_apis()
25
+ assert len(apis) > 10 and {"email-finder", "linkedin-profile"} <= {a["slug"] for a in apis}
26
+ best = c.best_plans("email-finder", limit=3)
27
+ assert best["api"] and len(best["plans"]) == 3 and best["plans"][0]["rank"] == 1
28
+ found = c.search_plans(query="bright data", sort="price", limit=5)
29
+ assert found["total"] > 0 and len(found["plans"]) == 5
30
+ assert all("bright data" in (p["provider"] + " " + p["plan"]).lower() for p in found["plans"])
31
+ one = c.provider("bright-data", plans="best")
32
+ assert one["provider"] == "Bright Data" and one["apis"]
33
+ with pytest.raises(DatacircleError) as raised:
34
+ c.best_plans("bright-data")
35
+ assert raised.value.status == 404 and "email-finder" in raised.value.body["slugs"]
36
+
37
+
38
+ def test_extension_live(app):
39
+ datacircle = app.config["datacircle"]
40
+ with app.app_context():
41
+ assert datacircle.list_apis()[0]["slug"]
42
+ assert len(datacircle.best_plans("linkedin-profile", limit=2)["plans"]) == 2
43
+ assert len(datacircle.search_plans(api="email-finder", sort="price", limit=3)["plans"]) == 3
44
+ assert "plans" not in datacircle.provider("bright-data", plans="none")["apis"][0]
45
+
46
+
47
+ def test_blueprint_live(app):
48
+ web = app.test_client()
49
+ assert web.get("/datacircle/apis").get_json()[0]["slug"]
50
+ assert len(web.get("/datacircle/apis/email-finder/best?limit=2").get_json()["plans"]) == 2
51
+ assert len(web.get("/datacircle/plans?api=email-finder&sort=price&limit=3").get_json()["plans"]) == 3
52
+ assert "plans" not in web.get("/datacircle/providers/bright-data?plans=none").get_json()["apis"][0]
53
+ answer = web.get("/datacircle/apis/nope/best")
54
+ assert answer.status_code == 404 and answer.get_json()["error"] == "no API has the slug nope"
55
+
56
+
57
+ def test_jinja_live(app):
58
+ with app.test_request_context():
59
+ html = render_template_string('{{ datacircle_best_plans("email-finder", limit=3) }}{{ datacircle_credit() }}')
60
+ assert html.count("<tr><td>") == 3 and 'href="https://datacircle.dev/best-email-finder-api"' in html
61
+ assert 'Scores and prices from <a href="https://datacircle.dev">Datacircle</a>.' in html