praesago 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,20 @@
1
+ name: ci
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ pull_request:
6
+ permissions:
7
+ contents: read
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ matrix:
13
+ python: ["3.10", "3.12", "3.14"]
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: actions/setup-python@v5
17
+ with:
18
+ python-version: ${{ matrix.python }}
19
+ - run: pip install pytest
20
+ - run: PYTHONPATH=src pytest -q tests
@@ -0,0 +1,36 @@
1
+ # Publishes to PyPI when a release tag v* is pushed. Uses PyPI trusted publishing: no token is stored anywhere.
2
+ name: publish
3
+ on:
4
+ push:
5
+ tags: ["v*"]
6
+ jobs:
7
+ build:
8
+ runs-on: ubuntu-latest
9
+ permissions:
10
+ contents: read
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: actions/setup-python@v5
14
+ with:
15
+ python-version: "3.12"
16
+ - run: pip install build pytest
17
+ - run: PYTHONPATH=src pytest -q tests
18
+ - name: Tag matches the package version
19
+ run: test "v$(python -c 'import sys; sys.path.insert(0, "src"); import praesago; print(praesago.__version__)')" = "${GITHUB_REF_NAME}"
20
+ - run: python -m build
21
+ - uses: actions/upload-artifact@v4
22
+ with:
23
+ name: dist
24
+ path: dist/
25
+ pypi:
26
+ needs: build
27
+ runs-on: ubuntu-latest
28
+ environment: pypi
29
+ permissions:
30
+ id-token: write
31
+ steps:
32
+ - uses: actions/download-artifact@v4
33
+ with:
34
+ name: dist
35
+ path: dist/
36
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ build/
5
+ .venv/
6
+ .pytest_cache/
7
+ .env
praesago-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Praesago
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.5
2
+ Name: praesago
3
+ Version: 0.1.0
4
+ Summary: Python client for the Praesago API: England and Wales property and area data (sold prices, rents, listings statistics, planning, crime, schools, flood).
5
+ Project-URL: Homepage, https://praesago.com
6
+ Project-URL: Documentation, https://praesago.com/docs/api
7
+ Project-URL: Source, https://github.com/Praesago/praesago-python
8
+ Project-URL: Pricing, https://praesago.com/pricing
9
+ Author: Praesago
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: api,england,house-prices,mcp,postcode,property,real-estate,wales
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Software Development :: Libraries
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+
21
+ # praesago (Python)
22
+
23
+ Python client for the [Praesago API](https://praesago.com/docs/api): property and area data for every postcode district in **England and Wales**. Sold prices, sector prices, price per square foot, rents and yields, weekly asking-market statistics, planning, crime, schools, flood risk, broadband and more, from official sources joined in one place.
24
+
25
+ No dependencies. Python 3.10 or later.
26
+
27
+ ```bash
28
+ pip install praesago
29
+ ```
30
+
31
+ ## Start
32
+
33
+ Create a key at <https://praesago.com/settings/api-keys>. Every account gets 500 free credits each month.
34
+
35
+ ```bash
36
+ export PRAESAGO_API_KEY=your-key
37
+ ```
38
+
39
+ ```python
40
+ from praesago import Praesago
41
+
42
+ client = Praesago() # reads PRAESAGO_API_KEY
43
+
44
+ e17 = client.district("E17") # everything for one district
45
+ print(e17["area_name"], e17["median_sold_price_gbp"])
46
+
47
+ print(client.last_credits) # Credits(charged=3, remaining=497)
48
+ ```
49
+
50
+ Try it without a key:
51
+
52
+ ```python
53
+ Praesago().demo() # real figures for E17
54
+ Praesago().catalogue() # every source, licence, period and coverage
55
+ ```
56
+
57
+ ## Examples
58
+
59
+ **Buy-to-let screen: districts with a 6% or higher asking yield under £250,000**
60
+
61
+ ```python
62
+ for row in client.screen(min_yield_pct=6, max_median_price_gbp=250_000, sort_by="yield", limit=10):
63
+ print(row)
64
+ ```
65
+
66
+ **Compare two districts**
67
+
68
+ ```python
69
+ client.compare("E17", "CF10")
70
+ ```
71
+
72
+ **Headline facts for many districts in one call** (1 credit for each district found, up to 50)
73
+
74
+ ```python
75
+ client.batch(["E17", "M14", "LS6", "CF24"])
76
+ ```
77
+
78
+ ## All methods
79
+
80
+ | Method | What it returns |
81
+ |---|---|
82
+ | `district(d, sections=None)` | Everything held for one district. `sections` limits the reply. |
83
+ | `context(d)` | Market context for a district |
84
+ | `sectors(d)` | Sold prices by postcode sector (a median needs 10 or more sales) |
85
+ | `sold_psf(d)` | Sold price per square foot (houses) |
86
+ | `rental(d)` | Rent and yield by bedrooms, rental demand, Local Housing Allowance |
87
+ | `price_history(d, months=None)` | Monthly HPI and yearly ONS medians |
88
+ | `planning(d, months=None)` | Planning activity (1 to 24 months) |
89
+ | `listings(d, channel=None, weeks=None, source=None)` | Weekly asking-market statistics (`sale` or `rent`) |
90
+ | `movers(channel=None, metric=None, limit=None)` | Biggest week-over-week changes (`price` or `inventory`) |
91
+ | `search(q, limit=None)` | Find districts by outcode or place name |
92
+ | `screen(**filters)` | Filter districts by price, rent, listings, price cuts, yield, region |
93
+ | `compare(a, b)` | Two districts side by side |
94
+ | `batch(districts)` | Headline facts for up to 50 districts |
95
+ | `catalogue()` | Sources and coverage (no key) |
96
+ | `demo()` | Fixed demo district (no key) |
97
+
98
+ Credit costs for each call are on the [pricing page](https://praesago.com/pricing).
99
+
100
+ ## Errors
101
+
102
+ Every error is a `PraesagoError` with `status`, `code` (stable, branch on it), `request_id` (quote it to support) and `retry_after` when the server sends it.
103
+
104
+ ```python
105
+ from praesago import InsufficientCreditsError, NotFoundError
106
+
107
+ try:
108
+ client.district("ZZ99")
109
+ except NotFoundError:
110
+ ... # not a district in England and Wales
111
+ except InsufficientCreditsError:
112
+ ... # buy credits at https://praesago.com/pricing
113
+ ```
114
+
115
+ The client retries rate limits (429) and server faults (5xx) twice, with back-off. Change it with `Praesago(max_retries=0)`.
116
+
117
+ ## Also
118
+
119
+ - MCP server for AI assistants: <https://praesago.com/docs/mcp>
120
+ - JavaScript client: [`praesago` on npm](https://www.npmjs.com/package/praesago)
121
+
122
+ MIT licence.
@@ -0,0 +1,102 @@
1
+ # praesago (Python)
2
+
3
+ Python client for the [Praesago API](https://praesago.com/docs/api): property and area data for every postcode district in **England and Wales**. Sold prices, sector prices, price per square foot, rents and yields, weekly asking-market statistics, planning, crime, schools, flood risk, broadband and more, from official sources joined in one place.
4
+
5
+ No dependencies. Python 3.10 or later.
6
+
7
+ ```bash
8
+ pip install praesago
9
+ ```
10
+
11
+ ## Start
12
+
13
+ Create a key at <https://praesago.com/settings/api-keys>. Every account gets 500 free credits each month.
14
+
15
+ ```bash
16
+ export PRAESAGO_API_KEY=your-key
17
+ ```
18
+
19
+ ```python
20
+ from praesago import Praesago
21
+
22
+ client = Praesago() # reads PRAESAGO_API_KEY
23
+
24
+ e17 = client.district("E17") # everything for one district
25
+ print(e17["area_name"], e17["median_sold_price_gbp"])
26
+
27
+ print(client.last_credits) # Credits(charged=3, remaining=497)
28
+ ```
29
+
30
+ Try it without a key:
31
+
32
+ ```python
33
+ Praesago().demo() # real figures for E17
34
+ Praesago().catalogue() # every source, licence, period and coverage
35
+ ```
36
+
37
+ ## Examples
38
+
39
+ **Buy-to-let screen: districts with a 6% or higher asking yield under £250,000**
40
+
41
+ ```python
42
+ for row in client.screen(min_yield_pct=6, max_median_price_gbp=250_000, sort_by="yield", limit=10):
43
+ print(row)
44
+ ```
45
+
46
+ **Compare two districts**
47
+
48
+ ```python
49
+ client.compare("E17", "CF10")
50
+ ```
51
+
52
+ **Headline facts for many districts in one call** (1 credit for each district found, up to 50)
53
+
54
+ ```python
55
+ client.batch(["E17", "M14", "LS6", "CF24"])
56
+ ```
57
+
58
+ ## All methods
59
+
60
+ | Method | What it returns |
61
+ |---|---|
62
+ | `district(d, sections=None)` | Everything held for one district. `sections` limits the reply. |
63
+ | `context(d)` | Market context for a district |
64
+ | `sectors(d)` | Sold prices by postcode sector (a median needs 10 or more sales) |
65
+ | `sold_psf(d)` | Sold price per square foot (houses) |
66
+ | `rental(d)` | Rent and yield by bedrooms, rental demand, Local Housing Allowance |
67
+ | `price_history(d, months=None)` | Monthly HPI and yearly ONS medians |
68
+ | `planning(d, months=None)` | Planning activity (1 to 24 months) |
69
+ | `listings(d, channel=None, weeks=None, source=None)` | Weekly asking-market statistics (`sale` or `rent`) |
70
+ | `movers(channel=None, metric=None, limit=None)` | Biggest week-over-week changes (`price` or `inventory`) |
71
+ | `search(q, limit=None)` | Find districts by outcode or place name |
72
+ | `screen(**filters)` | Filter districts by price, rent, listings, price cuts, yield, region |
73
+ | `compare(a, b)` | Two districts side by side |
74
+ | `batch(districts)` | Headline facts for up to 50 districts |
75
+ | `catalogue()` | Sources and coverage (no key) |
76
+ | `demo()` | Fixed demo district (no key) |
77
+
78
+ Credit costs for each call are on the [pricing page](https://praesago.com/pricing).
79
+
80
+ ## Errors
81
+
82
+ Every error is a `PraesagoError` with `status`, `code` (stable, branch on it), `request_id` (quote it to support) and `retry_after` when the server sends it.
83
+
84
+ ```python
85
+ from praesago import InsufficientCreditsError, NotFoundError
86
+
87
+ try:
88
+ client.district("ZZ99")
89
+ except NotFoundError:
90
+ ... # not a district in England and Wales
91
+ except InsufficientCreditsError:
92
+ ... # buy credits at https://praesago.com/pricing
93
+ ```
94
+
95
+ The client retries rate limits (429) and server faults (5xx) twice, with back-off. Change it with `Praesago(max_retries=0)`.
96
+
97
+ ## Also
98
+
99
+ - MCP server for AI assistants: <https://praesago.com/docs/mcp>
100
+ - JavaScript client: [`praesago` on npm](https://www.npmjs.com/package/praesago)
101
+
102
+ MIT licence.
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "praesago"
7
+ dynamic = ["version"]
8
+ description = "Python client for the Praesago API: England and Wales property and area data (sold prices, rents, listings statistics, planning, crime, schools, flood)."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "Praesago" }]
14
+ keywords = ["property", "real-estate", "england", "wales", "postcode", "house-prices", "api", "mcp"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ "Intended Audience :: Developers",
19
+ "Topic :: Software Development :: Libraries",
20
+ "Typing :: Typed",
21
+ ]
22
+ dependencies = []
23
+
24
+ [project.urls]
25
+ Homepage = "https://praesago.com"
26
+ Documentation = "https://praesago.com/docs/api"
27
+ Source = "https://github.com/Praesago/praesago-python"
28
+ Pricing = "https://praesago.com/pricing"
29
+
30
+ [tool.hatch.version]
31
+ path = "src/praesago/_version.py"
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["src/praesago"]
35
+
36
+ [tool.pytest.ini_options]
37
+ markers = ["live: calls the real API (no key needed for these)"]
@@ -0,0 +1,26 @@
1
+ """Praesago: England and Wales property and area data for code and AI agents."""
2
+
3
+ from ._version import __version__
4
+ from .client import Credits, Praesago
5
+ from .errors import (
6
+ AuthenticationError,
7
+ BadRequestError,
8
+ InsufficientCreditsError,
9
+ NotFoundError,
10
+ PraesagoError,
11
+ RateLimitError,
12
+ ServerError,
13
+ )
14
+
15
+ __all__ = [
16
+ "Praesago",
17
+ "Credits",
18
+ "PraesagoError",
19
+ "AuthenticationError",
20
+ "InsufficientCreditsError",
21
+ "NotFoundError",
22
+ "RateLimitError",
23
+ "BadRequestError",
24
+ "ServerError",
25
+ "__version__",
26
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,244 @@
1
+ """Client for the Praesago API (England and Wales property and area data)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import time
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from dataclasses import dataclass
12
+ from typing import Any, Iterable, Mapping, Optional
13
+
14
+ from ._version import __version__
15
+ from .errors import PraesagoError, error_for
16
+
17
+ DEFAULT_BASE_URL = "https://praesago.com"
18
+ RETRY_STATUSES = {429, 500, 502, 503, 504}
19
+
20
+
21
+ @dataclass
22
+ class Credits:
23
+ """Credit headers from the last keyed response. None when the server did not send them."""
24
+
25
+ charged: Optional[int] = None
26
+ remaining: Optional[int] = None
27
+
28
+
29
+ class Praesago:
30
+ """Praesago API client.
31
+
32
+ >>> from praesago import Praesago
33
+ >>> client = Praesago() # reads PRAESAGO_API_KEY
34
+ >>> client.district("E17")["area_name"]
35
+ 'Walthamstow'
36
+
37
+ Every method returns the ``data`` part of the reply. Errors raise a subclass of
38
+ :class:`praesago.PraesagoError`.
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ api_key: Optional[str] = None,
44
+ *,
45
+ base_url: str = DEFAULT_BASE_URL,
46
+ timeout: float = 30.0,
47
+ max_retries: int = 2,
48
+ ) -> None:
49
+ self.api_key = api_key if api_key is not None else os.environ.get("PRAESAGO_API_KEY")
50
+ self.base_url = base_url.rstrip("/")
51
+ self.timeout = timeout
52
+ self.max_retries = max_retries
53
+ self.last_credits = Credits()
54
+
55
+ # ---- district data -------------------------------------------------
56
+
57
+ def district(self, district: str, sections: Optional[Iterable[str]] = None) -> dict:
58
+ """Everything held for one postcode district. ``sections`` limits the reply (see :meth:`catalogue`)."""
59
+ params = {"sections": ",".join(sections)} if sections else None
60
+ return self._get(f"/api/agent/v1/district/{_q(district)}", params)
61
+
62
+ def context(self, district: str) -> dict:
63
+ """Property market context for a district."""
64
+ return self._get(f"/api/v1/districts/{_q(district)}/context")
65
+
66
+ def sectors(self, district: str) -> dict:
67
+ """Sold prices by postcode sector inside a district (a median needs 10 or more sales)."""
68
+ return self._get(f"/api/v1/districts/{_q(district)}/sectors")
69
+
70
+ def sold_psf(self, district: str) -> dict:
71
+ """Sold price per square foot (houses)."""
72
+ return self._get(f"/api/v1/districts/{_q(district)}/sold-psf")
73
+
74
+ def rental(self, district: str) -> dict:
75
+ """Rental yield and rent by bedroom count, rental demand and Local Housing Allowance rates."""
76
+ return self._get(f"/api/v1/districts/{_q(district)}/rental")
77
+
78
+ def price_history(self, district: str, months: Optional[int] = None) -> dict:
79
+ """Monthly HPI averages and yearly ONS medians."""
80
+ return self._get(f"/api/v1/districts/{_q(district)}/price-history", {"months": months})
81
+
82
+ def planning(self, district: str, months: Optional[int] = None) -> dict:
83
+ """Planning activity for a district (1 to 24 months, default 12)."""
84
+ return self._get(f"/api/v1/planning/{_q(district)}", {"months": months})
85
+
86
+ def listings(
87
+ self,
88
+ district: str,
89
+ channel: Optional[str] = None,
90
+ weeks: Optional[int] = None,
91
+ source: Optional[str] = None,
92
+ ) -> dict:
93
+ """Weekly asking-market statistics. ``channel`` is ``"sale"`` or ``"rent"``."""
94
+ return self._get(
95
+ f"/api/v1/listings/{_q(district)}", {"channel": channel, "weeks": weeks, "source": source}
96
+ )
97
+
98
+ # ---- many districts ------------------------------------------------
99
+
100
+ def movers(self, channel: Optional[str] = None, metric: Optional[str] = None, limit: Optional[int] = None) -> Any:
101
+ """Districts with the biggest week-over-week change. ``metric`` is ``"price"`` or ``"inventory"``."""
102
+ return self._get("/api/v1/listings/movers", {"channel": channel, "metric": metric, "limit": limit})
103
+
104
+ def search(self, q: str, limit: Optional[int] = None) -> Any:
105
+ """Find districts by outcode or place name."""
106
+ return self._get("/api/v1/districts/search", {"q": q, "limit": limit})
107
+
108
+ def screen(self, **filters: Any) -> Any:
109
+ """Screen districts, for example ``screen(min_yield_pct=6, max_median_price_gbp=250000, sort_by="yield")``.
110
+
111
+ Filters: min/max_median_price_gbp, min/max_asking_rent_pcm, min_sale_listings, min/max_price_cut_pct,
112
+ min/max_yield_pct, region, sort_by (price, rent, listings, price_cut, yield), order (asc, desc), limit.
113
+ """
114
+ return self._get("/api/v1/screen", filters)
115
+
116
+ def compare(self, a: str, b: str) -> dict:
117
+ """Compare two postcode districts."""
118
+ return self._get("/api/v1/compare", {"a": a, "b": b})
119
+
120
+ def batch(self, districts: Iterable[str]) -> Any:
121
+ """Headline facts for up to 50 districts in one call (1 credit for each district found)."""
122
+ return self._request("POST", "/api/v1/districts/batch", body={"districts": list(districts)})
123
+
124
+ # ---- no key needed -------------------------------------------------
125
+
126
+ def catalogue(self) -> dict:
127
+ """Sources, licences, periods and coverage. No key needed."""
128
+ return self._get("/api/v1/catalogue")
129
+
130
+ def demo(self) -> dict:
131
+ """Real figures for one fixed district. No key needed."""
132
+ return self._get("/api/v1/demo")
133
+
134
+ # ---- transport -----------------------------------------------------
135
+
136
+ def _get(self, path: str, params: Optional[Mapping[str, Any]] = None) -> Any:
137
+ return self._request("GET", path, params=params)
138
+
139
+ def _request(
140
+ self,
141
+ method: str,
142
+ path: str,
143
+ params: Optional[Mapping[str, Any]] = None,
144
+ body: Optional[Any] = None,
145
+ ) -> Any:
146
+ url = self.base_url + path
147
+ clean = {k: _param(v) for k, v in (params or {}).items() if v is not None}
148
+ if clean:
149
+ url += "?" + urllib.parse.urlencode(clean)
150
+ headers = {"Accept": "application/json", "User-Agent": f"praesago-python/{__version__}"}
151
+ if self.api_key:
152
+ headers["X-API-Key"] = self.api_key
153
+ data = None
154
+ if body is not None:
155
+ data = json.dumps(body).encode()
156
+ headers["Content-Type"] = "application/json"
157
+
158
+ attempt = 0
159
+ while True:
160
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
161
+ try:
162
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
163
+ self._read_credits(resp.headers)
164
+ return _unwrap(resp.status, resp.read(), resp.headers)
165
+ except urllib.error.HTTPError as exc:
166
+ self._read_credits(exc.headers)
167
+ raw = exc.read()
168
+ if exc.code in RETRY_STATUSES and attempt < self.max_retries:
169
+ attempt += 1
170
+ time.sleep(_retry_delay(exc.headers, attempt))
171
+ continue
172
+ raise _to_error(exc.code, raw, exc.headers) from None
173
+ except urllib.error.URLError as exc:
174
+ if attempt < self.max_retries:
175
+ attempt += 1
176
+ time.sleep(_retry_delay(None, attempt))
177
+ continue
178
+ raise PraesagoError(f"Network error: {exc.reason}", status=None, code="network") from None
179
+
180
+ def _read_credits(self, headers: Any) -> None:
181
+ if headers is None:
182
+ return
183
+ self.last_credits = Credits(
184
+ charged=_int(headers.get("X-Credits-Charged")),
185
+ remaining=_int(headers.get("X-Credits-Remaining")),
186
+ )
187
+
188
+
189
+ def _q(segment: str) -> str:
190
+ return urllib.parse.quote(segment.strip().upper().replace(" ", ""), safe="")
191
+
192
+
193
+ def _param(value: Any) -> str:
194
+ if isinstance(value, bool):
195
+ return "true" if value else "false"
196
+ return str(value)
197
+
198
+
199
+ def _int(value: Optional[str]) -> Optional[int]:
200
+ try:
201
+ return int(value) if value is not None else None
202
+ except ValueError:
203
+ return None
204
+
205
+
206
+ def _retry_delay(headers: Any, attempt: int) -> float:
207
+ if headers is not None:
208
+ after = headers.get("Retry-After")
209
+ if after:
210
+ try:
211
+ return min(float(after), 30.0)
212
+ except ValueError:
213
+ pass
214
+ return min(0.5 * 2 ** (attempt - 1), 8.0)
215
+
216
+
217
+ def _unwrap(status: int, raw: bytes, headers: Any) -> Any:
218
+ payload = _json(raw)
219
+ if not isinstance(payload, dict):
220
+ raise PraesagoError("The server sent a reply that is not JSON", status=status, code="bad_response")
221
+ if payload.get("success") is False:
222
+ raise _to_error(status, raw, headers)
223
+ return payload.get("data")
224
+
225
+
226
+ def _to_error(status: int, raw: bytes, headers: Any) -> PraesagoError:
227
+ payload = _json(raw)
228
+ if isinstance(payload, dict):
229
+ return error_for(
230
+ status,
231
+ message=payload.get("error") or f"HTTP {status}",
232
+ code=payload.get("code"),
233
+ request_id=payload.get("request_id"),
234
+ details=payload,
235
+ retry_after=_int(headers.get("Retry-After")) if headers is not None else None,
236
+ )
237
+ return error_for(status, message=f"HTTP {status} (reply is not JSON)", code=None)
238
+
239
+
240
+ def _json(raw: bytes) -> Any:
241
+ try:
242
+ return json.loads(raw.decode("utf-8"))
243
+ except (UnicodeDecodeError, json.JSONDecodeError):
244
+ return None
@@ -0,0 +1,73 @@
1
+ """Errors raised by the Praesago client. Branch on ``code`` (stable), not on the message text."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+
8
+ class PraesagoError(Exception):
9
+ def __init__(
10
+ self,
11
+ message: str,
12
+ *,
13
+ status: Optional[int] = None,
14
+ code: Optional[str] = None,
15
+ request_id: Optional[str] = None,
16
+ details: Any = None,
17
+ retry_after: Optional[int] = None,
18
+ ) -> None:
19
+ super().__init__(message)
20
+ self.message = message
21
+ self.status = status
22
+ self.code = code
23
+ self.request_id = request_id
24
+ self.details = details
25
+ self.retry_after = retry_after
26
+
27
+ def __str__(self) -> str:
28
+ extra = ", ".join(
29
+ f"{k}={v}" for k, v in (("status", self.status), ("code", self.code), ("request_id", self.request_id)) if v
30
+ )
31
+ return f"{self.message} ({extra})" if extra else self.message
32
+
33
+
34
+ class AuthenticationError(PraesagoError):
35
+ """401: the key is missing or not valid. Create one at https://praesago.com/settings/api-keys."""
36
+
37
+
38
+ class InsufficientCreditsError(PraesagoError):
39
+ """402: not enough credits. Buy more at https://praesago.com/pricing."""
40
+
41
+
42
+ class NotFoundError(PraesagoError):
43
+ """404: no such postcode district (England and Wales only)."""
44
+
45
+
46
+ class RateLimitError(PraesagoError):
47
+ """429: too many requests. ``retry_after`` gives seconds when the server sends it."""
48
+
49
+
50
+ class BadRequestError(PraesagoError):
51
+ """400: a parameter is not valid."""
52
+
53
+
54
+ class ServerError(PraesagoError):
55
+ """5xx: a fault on the Praesago side. Quote ``request_id`` when you write to support."""
56
+
57
+
58
+ def error_for(status: int, *, message: str, code: Optional[str], **kw: Any) -> PraesagoError:
59
+ if status == 401:
60
+ cls = AuthenticationError
61
+ elif status == 402:
62
+ cls = InsufficientCreditsError
63
+ elif status == 404:
64
+ cls = NotFoundError
65
+ elif status == 429:
66
+ cls = RateLimitError
67
+ elif status == 400:
68
+ cls = BadRequestError
69
+ elif status >= 500:
70
+ cls = ServerError
71
+ else:
72
+ cls = PraesagoError
73
+ return cls(message, status=status, code=code, **kw)
File without changes
@@ -0,0 +1,187 @@
1
+ import json
2
+ import threading
3
+ from http.server import BaseHTTPRequestHandler, HTTPServer
4
+
5
+ import pytest
6
+
7
+ from praesago import (
8
+ AuthenticationError,
9
+ InsufficientCreditsError,
10
+ NotFoundError,
11
+ Praesago,
12
+ PraesagoError,
13
+ RateLimitError,
14
+ )
15
+
16
+
17
+ class Stub:
18
+ """A local HTTP server that records requests and replies from a queue."""
19
+
20
+ def __init__(self):
21
+ self.requests = []
22
+ self.replies = []
23
+ stub = self
24
+
25
+ class Handler(BaseHTTPRequestHandler):
26
+ def _serve(self):
27
+ length = int(self.headers.get("Content-Length") or 0)
28
+ body = self.rfile.read(length) if length else b""
29
+ stub.requests.append(
30
+ {"method": self.command, "path": self.path, "headers": {k.lower(): v for k, v in self.headers.items()}, "body": body}
31
+ )
32
+ status, payload, headers = stub.replies.pop(0) if stub.replies else (200, {"success": True, "data": {}}, {})
33
+ raw = payload if isinstance(payload, bytes) else json.dumps(payload).encode()
34
+ self.send_response(status)
35
+ for k, v in headers.items():
36
+ self.send_header(k, v)
37
+ self.send_header("Content-Length", str(len(raw)))
38
+ self.end_headers()
39
+ self.wfile.write(raw)
40
+
41
+ do_GET = _serve
42
+ do_POST = _serve
43
+
44
+ def log_message(self, *a):
45
+ pass
46
+
47
+ self.server = HTTPServer(("127.0.0.1", 0), Handler)
48
+ self.url = f"http://127.0.0.1:{self.server.server_port}"
49
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
50
+
51
+ def reply(self, status, payload, headers=None):
52
+ self.replies.append((status, payload, headers or {}))
53
+
54
+
55
+ @pytest.fixture
56
+ def stub():
57
+ s = Stub()
58
+ yield s
59
+ s.server.shutdown()
60
+
61
+
62
+ def client(stub, **kw):
63
+ return Praesago("test-key", base_url=stub.url, **kw)
64
+
65
+
66
+ def test_district_path_key_and_unwrap(stub):
67
+ stub.reply(200, {"success": True, "data": {"district": "E17"}}, {"X-Credits-Charged": "3", "X-Credits-Remaining": "497"})
68
+ c = client(stub)
69
+ assert c.district(" e17 ") == {"district": "E17"}
70
+ req = stub.requests[0]
71
+ assert req["path"] == "/api/agent/v1/district/E17"
72
+ assert req["headers"]["x-api-key"] == "test-key"
73
+ assert req["headers"]["user-agent"].startswith("praesago-python/")
74
+ assert c.last_credits.charged == 3 and c.last_credits.remaining == 497
75
+
76
+
77
+ def test_sections_and_none_params_dropped(stub):
78
+ c = client(stub)
79
+ c.district("E17", sections=["property", "crime"])
80
+ c.listings("E17", channel="rent")
81
+ assert stub.requests[0]["path"] == "/api/agent/v1/district/E17?sections=property%2Ccrime"
82
+ assert stub.requests[1]["path"] == "/api/v1/listings/E17?channel=rent"
83
+
84
+
85
+ @pytest.mark.parametrize(
86
+ "call,path",
87
+ [
88
+ (lambda c: c.context("E17"), "/api/v1/districts/E17/context"),
89
+ (lambda c: c.sectors("E17"), "/api/v1/districts/E17/sectors"),
90
+ (lambda c: c.sold_psf("E17"), "/api/v1/districts/E17/sold-psf"),
91
+ (lambda c: c.rental("E17"), "/api/v1/districts/E17/rental"),
92
+ (lambda c: c.price_history("E17", months=24), "/api/v1/districts/E17/price-history?months=24"),
93
+ (lambda c: c.planning("E17", months=6), "/api/v1/planning/E17?months=6"),
94
+ (lambda c: c.movers(metric="inventory"), "/api/v1/listings/movers?metric=inventory"),
95
+ (lambda c: c.search("Walthamstow", limit=5), "/api/v1/districts/search?q=Walthamstow&limit=5"),
96
+ (lambda c: c.screen(min_yield_pct=6, sort_by="yield"), "/api/v1/screen?min_yield_pct=6&sort_by=yield"),
97
+ (lambda c: c.compare("E17", "E18"), "/api/v1/compare?a=E17&b=E18"),
98
+ (lambda c: c.catalogue(), "/api/v1/catalogue"),
99
+ (lambda c: c.demo(), "/api/v1/demo"),
100
+ ],
101
+ )
102
+ def test_paths(stub, call, path):
103
+ call(client(stub))
104
+ assert stub.requests[0]["path"] == path
105
+
106
+
107
+ def test_batch_posts_json(stub):
108
+ client(stub).batch(["E17", "CF10"])
109
+ req = stub.requests[0]
110
+ assert req["method"] == "POST" and req["path"] == "/api/v1/districts/batch"
111
+ assert json.loads(req["body"]) == {"districts": ["E17", "CF10"]}
112
+ assert req["headers"]["content-type"] == "application/json"
113
+
114
+
115
+ @pytest.mark.parametrize(
116
+ "status,code,cls",
117
+ [(401, "invalid_key", AuthenticationError), (402, "insufficient_credits", InsufficientCreditsError), (404, "not_found", NotFoundError)],
118
+ )
119
+ def test_errors_map_to_classes(stub, status, code, cls):
120
+ stub.reply(status, {"success": False, "data": None, "error": "nope", "code": code, "request_id": "req_1"})
121
+ with pytest.raises(cls) as exc:
122
+ client(stub).context("ZZ99")
123
+ assert exc.value.code == code and exc.value.request_id == "req_1" and exc.value.status == status
124
+
125
+
126
+ def test_429_retries_then_succeeds(stub):
127
+ stub.reply(429, {"success": False, "error": "slow", "code": "rate_limited"}, {"Retry-After": "0"})
128
+ stub.reply(200, {"success": True, "data": [1]})
129
+ assert client(stub).search("x") == [1]
130
+ assert len(stub.requests) == 2
131
+
132
+
133
+ def test_429_gives_up(stub):
134
+ for _ in range(3):
135
+ stub.reply(429, {"success": False, "error": "slow", "code": "rate_limited"}, {"Retry-After": "0"})
136
+ with pytest.raises(RateLimitError):
137
+ client(stub, max_retries=2).search("x")
138
+ assert len(stub.requests) == 3
139
+
140
+
141
+ def test_non_json_reply(stub):
142
+ stub.reply(404, b"<!DOCTYPE html>")
143
+ with pytest.raises(NotFoundError):
144
+ client(stub).context("E17")
145
+
146
+
147
+ def test_no_key_sends_no_header(stub, monkeypatch):
148
+ monkeypatch.delenv("PRAESAGO_API_KEY", raising=False)
149
+ Praesago(base_url=stub.url).demo()
150
+ assert "x-api-key" not in stub.requests[0]["headers"]
151
+
152
+
153
+ def test_env_key(stub, monkeypatch):
154
+ monkeypatch.setenv("PRAESAGO_API_KEY", "from-env")
155
+ Praesago(base_url=stub.url).demo()
156
+ assert stub.requests[0]["headers"]["x-api-key"] == "from-env"
157
+
158
+
159
+ # ---- live calls: only endpoints that need no key -----------------------
160
+
161
+
162
+ @pytest.mark.live
163
+ def test_live_demo_and_catalogue():
164
+ c = Praesago(api_key="", max_retries=0)
165
+ try:
166
+ demo = c.demo()
167
+ except PraesagoError as exc:
168
+ if exc.status == 403:
169
+ pytest.skip("Cloudflare blocks keyless calls from this network (cloud runners)")
170
+ raise
171
+ assert demo["district"]["district"] == "E17"
172
+ assert "England and Wales" in c.catalogue()["coverage"]
173
+
174
+
175
+ @pytest.mark.live
176
+ def test_live_bad_key_is_auth_error():
177
+ with pytest.raises(AuthenticationError) as exc:
178
+ Praesago(api_key="not-a-real-key", max_retries=0).context("E17")
179
+ assert exc.value.code == "invalid_key"
180
+
181
+
182
+ @pytest.mark.live
183
+ def test_live_full_district_path_exists():
184
+ # 401 (JSON) proves the route exists; a wrong path gives a 404 web page.
185
+ with pytest.raises(PraesagoError) as exc:
186
+ Praesago(api_key="not-a-real-key", max_retries=0).district("E17")
187
+ assert exc.value.status == 401