pastclimate 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.
- pastclimate-0.1.0/.gitignore +87 -0
- pastclimate-0.1.0/LICENSE +21 -0
- pastclimate-0.1.0/PKG-INFO +302 -0
- pastclimate-0.1.0/README.md +277 -0
- pastclimate-0.1.0/examples/quickstart.py +54 -0
- pastclimate-0.1.0/pyproject.toml +42 -0
- pastclimate-0.1.0/src/pastclimate/__init__.py +117 -0
- pastclimate-0.1.0/src/pastclimate/_http.py +138 -0
- pastclimate-0.1.0/src/pastclimate/_version.py +1 -0
- pastclimate-0.1.0/src/pastclimate/client.py +558 -0
- pastclimate-0.1.0/src/pastclimate/errors.py +216 -0
- pastclimate-0.1.0/src/pastclimate/models.py +498 -0
- pastclimate-0.1.0/src/pastclimate/py.typed +0 -0
- pastclimate-0.1.0/tests/__init__.py +8 -0
- pastclimate-0.1.0/tests/helpers.py +221 -0
- pastclimate-0.1.0/tests/test_client.py +117 -0
- pastclimate-0.1.0/tests/test_csv.py +70 -0
- pastclimate-0.1.0/tests/test_errors.py +174 -0
- pastclimate-0.1.0/tests/test_local_server.py +122 -0
- pastclimate-0.1.0/tests/test_methods.py +322 -0
- pastclimate-0.1.0/tests/test_retries.py +206 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# --- OS ---
|
|
2
|
+
.DS_Store
|
|
3
|
+
|
|
4
|
+
# --- Node ---
|
|
5
|
+
node_modules/
|
|
6
|
+
dist/
|
|
7
|
+
.astro/
|
|
8
|
+
.wrangler
|
|
9
|
+
.vite-cache/
|
|
10
|
+
|
|
11
|
+
# --- Python ---
|
|
12
|
+
__pycache__/
|
|
13
|
+
*.py[cod]
|
|
14
|
+
.venv/
|
|
15
|
+
venv/
|
|
16
|
+
*.egg-info/
|
|
17
|
+
.pytest_cache/
|
|
18
|
+
.mypy_cache/
|
|
19
|
+
|
|
20
|
+
# --- Raw & processed data (never committed — too large, regenerated locally) ---
|
|
21
|
+
# Leading slash anchors these to the project root — unanchored 'data/' also
|
|
22
|
+
# matched src/data/ (industry-page content), silently untracking it.
|
|
23
|
+
# No trailing slash so it also ignores the /data symlink (git sees a symlink
|
|
24
|
+
# as a file, and a trailing-slash pattern only matches directories).
|
|
25
|
+
/data
|
|
26
|
+
/backups/
|
|
27
|
+
.tmp/
|
|
28
|
+
*.nc
|
|
29
|
+
*.nc.zip
|
|
30
|
+
*.grib
|
|
31
|
+
*.parquet
|
|
32
|
+
|
|
33
|
+
# --- Databases & catalogs (generated) ---
|
|
34
|
+
*.sqlite
|
|
35
|
+
*.sqlite3
|
|
36
|
+
*.db
|
|
37
|
+
|
|
38
|
+
# --- Logs & reports (generated) ---
|
|
39
|
+
*.log
|
|
40
|
+
logs/
|
|
41
|
+
|
|
42
|
+
# --- Credentials ---
|
|
43
|
+
# `.cdsapirc` alone missed the real files: the multi-account submitter reads
|
|
44
|
+
# ~/.cdsapirc-account1..4, and a copy placed in the repo would have been tracked.
|
|
45
|
+
# A live CDS key reached a commit that way on 2026-08-03 (docs/SECRET-REMEDIATION-2026-08-03.md).
|
|
46
|
+
.cdsapirc
|
|
47
|
+
.cdsapirc-*
|
|
48
|
+
*.cdsapirc
|
|
49
|
+
# The placeholder template is the one file that must stay tracked.
|
|
50
|
+
!era5_submitter/cdsapirc.example
|
|
51
|
+
.env
|
|
52
|
+
.env.*
|
|
53
|
+
.dev.vars
|
|
54
|
+
.dev.vars.local
|
|
55
|
+
|
|
56
|
+
# site-health-check.mjs output (scripts/site-health-check.mjs)
|
|
57
|
+
/reports/
|
|
58
|
+
|
|
59
|
+
# --- Personal working notes (never committed) ---
|
|
60
|
+
Ignore_Sandeep_Notes
|
|
61
|
+
|
|
62
|
+
# Per-country D1 sync payloads written to the repo root by
|
|
63
|
+
# scripts/builder/sync_d1_countries.py. Generated artifacts, not source: the US
|
|
64
|
+
# one is ~90k statements / 6MB, and it is regenerated from the local mirror
|
|
65
|
+
# every run. Anchored to the root because that is where the script writes them
|
|
66
|
+
# (output_file = f"d1_remote_{cc}.sql", relative to the working directory).
|
|
67
|
+
/d1_remote_*.sql
|
|
68
|
+
|
|
69
|
+
# Local dev links to the external drive (see memory: data lives on D:).
|
|
70
|
+
# Committed by accident once — these are absolute D:\ paths, broken anywhere else.
|
|
71
|
+
# (The actual rule is /data at the top of this file — a bare `data` used to
|
|
72
|
+
# live here too, which matches that name at ANY depth and was silently
|
|
73
|
+
# blocking every file under src/data/ from ever being tracked. Found when
|
|
74
|
+
# ehabDefaults.js never showed up in git status despite existing on disk.)
|
|
75
|
+
.wrangler
|
|
76
|
+
|
|
77
|
+
# Vendored Tailwind docs pulled by .agents/skills/tailwind-4-docs's
|
|
78
|
+
# sync_tailwind_docs.py — 236 third-party .mdx files (~5MB) regenerated on
|
|
79
|
+
# demand from the upstream repo, so it is a local cache, not source. The
|
|
80
|
+
# skill's own notes and docs-source.txt (which pins the synced commit) ARE
|
|
81
|
+
# tracked; only the payload is ignored.
|
|
82
|
+
.agents/skills/tailwind-4-docs/references/docs/
|
|
83
|
+
.agents/skills/tailwind-4-docs/references/docs-index.tsx
|
|
84
|
+
.batch-drafts
|
|
85
|
+
|
|
86
|
+
# Timestamped local backups taken before destructive edits. Never committed.
|
|
87
|
+
.backups/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PastClimate
|
|
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,302 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pastclimate
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python client for the PastClimate API: historical daily, hourly, monthly and yearly weather, climate normals and records.
|
|
5
|
+
Project-URL: Documentation, https://developer.pastclimate.com/api/
|
|
6
|
+
Project-URL: Source, https://github.com/pastclimate/pastclimate-python
|
|
7
|
+
Author: PastClimate
|
|
8
|
+
License: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: api,climate,historical weather,pastclimate,weather
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# pastclimate (Python)
|
|
27
|
+
|
|
28
|
+
Official Python client for the [PastClimate API](https://developer.pastclimate.com/api/): historical daily, hourly, monthly and yearly weather, climate normals and records for places around the world.
|
|
29
|
+
|
|
30
|
+
- No dependencies. Python 3.9 or newer.
|
|
31
|
+
- Typed: ships `py.typed`, every response is a dataclass.
|
|
32
|
+
- One method per API operation, typed errors, automatic retries.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install pastclimate
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Quickstart
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from pastclimate import Client
|
|
44
|
+
|
|
45
|
+
client = Client() # reads the PASTCLIMATE_API_KEY environment variable
|
|
46
|
+
|
|
47
|
+
resp = client.get_daily("gb/london", start="2024-01-01", end="2024-01-31")
|
|
48
|
+
|
|
49
|
+
for row in resp.data:
|
|
50
|
+
print(row.date, row.daily_min_temp, row.daily_max_temp, row.daily_total_rain)
|
|
51
|
+
|
|
52
|
+
print("credits used:", resp.credits_used)
|
|
53
|
+
print("credits remaining:", resp.credits_remaining)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Get a key from your PastClimate account. Never put a key in source code or in a URL. Call the API from a server or a script, not from a browser: the API does not accept browser calls.
|
|
57
|
+
|
|
58
|
+
## Configuration
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
client = Client(
|
|
62
|
+
api_key="YOUR_API_KEY", # default: the PASTCLIMATE_API_KEY environment variable
|
|
63
|
+
base_url="https://api.pastclimate.com",
|
|
64
|
+
timeout=30.0, # seconds per HTTP attempt; None waits forever
|
|
65
|
+
max_retries=2, # see "Retries"
|
|
66
|
+
max_retry_after=60.0, # longest Retry-After (seconds) to sleep through
|
|
67
|
+
)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
If no key is passed and the environment variable is not set, `Client()` raises `AuthenticationError` with code `missing_key`.
|
|
71
|
+
|
|
72
|
+
Every request sends `User-Agent: pastclimate-python/<version>` and `Authorization: Bearer <key>`.
|
|
73
|
+
|
|
74
|
+
## Choosing a place
|
|
75
|
+
|
|
76
|
+
Every data method takes the place in one of two ways:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
client.get_monthly("gb/london") # a location id
|
|
80
|
+
client.get_monthly(lat=51.5, lon=-0.12, country="gb") # a point and its country
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
A point is snapped to the nearest place in that country; `resp.location.requested` shows the point you sent and the distance. Find ids with `search_locations`. Location ids and the look-up calls are free, but they still count toward your request limits.
|
|
84
|
+
|
|
85
|
+
## Responses
|
|
86
|
+
|
|
87
|
+
Every successful call returns an `ApiResponse` with:
|
|
88
|
+
|
|
89
|
+
| Attribute | Meaning |
|
|
90
|
+
|---|---|
|
|
91
|
+
| `data` | The parsed `data`: a list of rows, or one object. |
|
|
92
|
+
| `meta` | The parsed `meta`: `credits`, `credits_remaining`, `methodology_version`, plus fields for the call (such as `units`). |
|
|
93
|
+
| `location` | The place the numbers are for, or `None` for calls that are not about one place. |
|
|
94
|
+
| `credits_used` | Credits this call used. |
|
|
95
|
+
| `credits_remaining` | Credits you can still spend. |
|
|
96
|
+
| `rate_limit` | `limit`, `remaining`, `reset` from the `RateLimit-*` headers (`None` when absent). |
|
|
97
|
+
| `status_code`, `headers` | The HTTP status and the response headers (lower-case names). |
|
|
98
|
+
| `raw` | The whole decoded JSON body, including fields this SDK does not model yet. |
|
|
99
|
+
|
|
100
|
+
The SDK never computes or assumes credit costs. Read them from the response.
|
|
101
|
+
|
|
102
|
+
Fields are named exactly like the API's JSON fields. The API can add new fields at any time; the models ignore ones they do not know and `raw` keeps them.
|
|
103
|
+
|
|
104
|
+
## Methods
|
|
105
|
+
|
|
106
|
+
### `search_locations(q, *, country=None)`
|
|
107
|
+
|
|
108
|
+
Search places by the start of a name (at least 3 characters). Free.
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
resp = client.search_locations("lon", country="gb")
|
|
112
|
+
for hit in resp.data:
|
|
113
|
+
print(hit.id, hit.name, hit.population, hit.weather_available)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### `nearest_location(lat, lon, country)`
|
|
117
|
+
|
|
118
|
+
The place nearest a point, inside one country. Free.
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
resp = client.nearest_location(51.5, -0.12, "gb")
|
|
122
|
+
print(resp.data.id, resp.data.requested.distance_km)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### `get_location(location_id)`
|
|
126
|
+
|
|
127
|
+
One place by id. Free.
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
resp = client.get_location("gb/london")
|
|
131
|
+
print(resp.data.name, resp.data.timezone, resp.data.coverage.first_year)
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### `get_daily(location=None, *, start, end, lat=None, lon=None, country=None, units=None, format="json")`
|
|
135
|
+
|
|
136
|
+
Daily values from `start` to `end` inclusive. Dates can be `datetime.date` objects or `"YYYY-MM-DD"` strings.
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
resp = client.get_daily("gb/london", start="2024-01-01", end="2024-01-31", units="imperial")
|
|
140
|
+
print(resp.meta.units.temperature) # "F"
|
|
141
|
+
print(resp.data[0].daily_max_temp)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### `get_hourly(location=None, *, date, days=None, lat=None, lon=None, country=None, units=None, format="json")`
|
|
145
|
+
|
|
146
|
+
Hourly values for `days` consecutive local days starting at `date`. How many days one call may ask for, and how far back it can go, depends on your plan; call `get_me()` to see your plan's limits.
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
resp = client.get_hourly("gb/london", date="2024-01-15", days=1)
|
|
150
|
+
for row in resp.data:
|
|
151
|
+
print(row.timestamp_utc, row.temperature, row.precipitation)
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
### `get_monthly(location=None, *, lat=None, lon=None, country=None, units=None)`
|
|
155
|
+
|
|
156
|
+
One row per calendar month on file, oldest first.
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
resp = client.get_monthly("gb/london")
|
|
160
|
+
print(resp.data[-1].year, resp.data[-1].month, resp.data[-1].monthly_total_rain)
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
### `get_yearly(location=None, *, lat=None, lon=None, country=None, units=None)`
|
|
164
|
+
|
|
165
|
+
One row per calendar year on file, oldest first.
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
resp = client.get_yearly("gb/london")
|
|
169
|
+
print([(r.year, r.yearly_avg_temp) for r in resp.data])
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
### `get_normals(location=None, *, month=None, lat=None, lon=None, country=None, units=None)`
|
|
173
|
+
|
|
174
|
+
Climate normals: `data.monthly` and `data.day_of_year`. `month` (1 to 12) narrows both.
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
resp = client.get_normals("gb/london", month=7)
|
|
178
|
+
print(resp.data.monthly[0].avg_temp, len(resp.data.day_of_year))
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### `get_records(location=None, *, lat=None, lon=None, country=None, units=None)`
|
|
182
|
+
|
|
183
|
+
The hottest, coldest, wettest and windiest day on file.
|
|
184
|
+
|
|
185
|
+
```python
|
|
186
|
+
resp = client.get_records("gb/london")
|
|
187
|
+
for rec in resp.data:
|
|
188
|
+
print(rec.metric, rec.value, rec.unit, rec.occurred_on)
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### `get_coverage(country=None)`
|
|
192
|
+
|
|
193
|
+
Countries served, with the first year and last published day. Free.
|
|
194
|
+
|
|
195
|
+
```python
|
|
196
|
+
resp = client.get_coverage("gb")
|
|
197
|
+
print(resp.data.countries[0].last_date)
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### `get_me()`
|
|
201
|
+
|
|
202
|
+
Your plan, credit balance and limits. Free.
|
|
203
|
+
|
|
204
|
+
```python
|
|
205
|
+
resp = client.get_me()
|
|
206
|
+
print(resp.data.plan.id, resp.meta.credits_remaining, resp.data.rate_limit.per_minute)
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
## Units
|
|
210
|
+
|
|
211
|
+
`units="metric"` (the default) or `units="imperial"` on every data method. Field names do not change; the unit of each value is in `meta.units`.
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
resp = client.get_records("gb/london", units="imperial")
|
|
215
|
+
print(resp.meta.units.temperature, resp.meta.units.wind_speed) # F mph
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
## CSV
|
|
219
|
+
|
|
220
|
+
`get_daily` and `get_hourly` accept `format="csv"` and then return a `CsvResponse` instead:
|
|
221
|
+
|
|
222
|
+
```python
|
|
223
|
+
resp = client.get_daily("gb/london", start="2023-01-01", end="2023-12-31", format="csv")
|
|
224
|
+
with open("london-2023.csv", "w", newline="") as fh:
|
|
225
|
+
fh.write(resp.text)
|
|
226
|
+
print(resp.credits_used, resp.credits_remaining, resp.rate_limit.remaining)
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
CSV has no `meta`, so `credits_used` and `credits_remaining` come from the `X-Credits-*` headers. Errors are still JSON and raise the usual typed errors.
|
|
230
|
+
|
|
231
|
+
## Errors
|
|
232
|
+
|
|
233
|
+
Every error is a `PastClimateError`. Errors from an HTTP answer are `ApiError` and carry `code`, `message`, `docs_url` and `status`, plus `retry_after`, `upgrade_url`, `rate_limit` and `headers`. There is one class per category:
|
|
234
|
+
|
|
235
|
+
| Class | Codes |
|
|
236
|
+
|---|---|
|
|
237
|
+
| `AuthenticationError` | `missing_key`, `invalid_key`, `key_revoked`, `email_not_verified`, `account_suspended` |
|
|
238
|
+
| `InvalidRequestError` | `invalid_request`, `range_too_large`, `key_in_query`, `method_not_allowed`, `cors_not_supported` |
|
|
239
|
+
| `NotFoundError` | `location_not_found`, `not_published`, `location_blocked`, `not_found` |
|
|
240
|
+
| `PlanRequiredError` | `plan_required` |
|
|
241
|
+
| `RateLimitError` | `rate_limited`, `daily_request_cap_reached` |
|
|
242
|
+
| `QuotaExceededError` | `quota_exceeded` |
|
|
243
|
+
| `ServerError` | `internal_error`, `api_disabled`, `metering_unavailable` |
|
|
244
|
+
|
|
245
|
+
A code the SDK does not know yet is mapped by HTTP status, or raised as plain `ApiError`, so new codes never crash your code. `NetworkError` means no answer arrived (connection failure or timeout) after the retries ran out. A request the SDK refuses before sending (for example `get_monthly()` with no place) raises `InvalidRequestError` with `status == 0`.
|
|
246
|
+
|
|
247
|
+
```python
|
|
248
|
+
from pastclimate import (
|
|
249
|
+
Client, NotFoundError, QuotaExceededError, RateLimitError, ApiError, NetworkError,
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
client = Client()
|
|
253
|
+
try:
|
|
254
|
+
resp = client.get_daily("gb/nowhere", start="2024-01-01", end="2024-01-31")
|
|
255
|
+
except NotFoundError as err:
|
|
256
|
+
print("Unknown place or no data:", err.code, err.message)
|
|
257
|
+
except QuotaExceededError as err:
|
|
258
|
+
print("Out of credits. Upgrade here:", err.upgrade_url)
|
|
259
|
+
except RateLimitError as err:
|
|
260
|
+
print("Slow down. Try again in", err.retry_after, "seconds")
|
|
261
|
+
except ApiError as err:
|
|
262
|
+
print(err.status, err.code, err.message, err.docs_url)
|
|
263
|
+
except NetworkError as err:
|
|
264
|
+
print("Could not reach the API:", err)
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
Branch on `code`, not on `message`. Failed requests are not charged.
|
|
268
|
+
|
|
269
|
+
## Retries
|
|
270
|
+
|
|
271
|
+
The client retries automatically, up to `max_retries` times (default 2):
|
|
272
|
+
|
|
273
|
+
- **429 with a `Retry-After` header:** waits that many seconds, then retries.
|
|
274
|
+
- **5xx and network errors (including timeouts):** retries with exponential backoff and jitter.
|
|
275
|
+
- **Never retried:** every other 4xx, and a 429 without `Retry-After`. A 429 without `Retry-After` means waiting will not help, for example when the free credits are permanently used up.
|
|
276
|
+
|
|
277
|
+
If `Retry-After` is longer than `max_retry_after` (default 60 seconds), the error is raised straight away instead of sleeping, so a call never hangs for hours, for example until the daily limit resets. Read `err.retry_after` and decide for yourself. Set `max_retries=0` to turn retries off.
|
|
278
|
+
|
|
279
|
+
## Using your own HTTP library
|
|
280
|
+
|
|
281
|
+
The default transport uses only the standard library. To use `requests`, `httpx` or a test double, pass `transport`, a callable that takes an `HTTPRequest` and returns an `HTTPResponse` (status, lower-case header names, body bytes). It should raise `OSError` (for example `ConnectionError` or `TimeoutError`) when no answer arrives, and should not raise for non-2xx statuses.
|
|
282
|
+
|
|
283
|
+
```python
|
|
284
|
+
from pastclimate import Client, HTTPRequest, HTTPResponse
|
|
285
|
+
|
|
286
|
+
def transport(request: HTTPRequest) -> HTTPResponse:
|
|
287
|
+
...
|
|
288
|
+
|
|
289
|
+
client = Client("YOUR_API_KEY", transport=transport)
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
## Development
|
|
293
|
+
|
|
294
|
+
```bash
|
|
295
|
+
python3 -m unittest discover -s tests -t .
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
The tests use a mocked transport, plus one file that talks to a local server on 127.0.0.1. `examples/quickstart.py` calls the live API, and only when `PASTCLIMATE_API_KEY` is set.
|
|
299
|
+
|
|
300
|
+
## License
|
|
301
|
+
|
|
302
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
# pastclimate (Python)
|
|
2
|
+
|
|
3
|
+
Official Python client for the [PastClimate API](https://developer.pastclimate.com/api/): historical daily, hourly, monthly and yearly weather, climate normals and records for places around the world.
|
|
4
|
+
|
|
5
|
+
- No dependencies. Python 3.9 or newer.
|
|
6
|
+
- Typed: ships `py.typed`, every response is a dataclass.
|
|
7
|
+
- One method per API operation, typed errors, automatic retries.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install pastclimate
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quickstart
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from pastclimate import Client
|
|
19
|
+
|
|
20
|
+
client = Client() # reads the PASTCLIMATE_API_KEY environment variable
|
|
21
|
+
|
|
22
|
+
resp = client.get_daily("gb/london", start="2024-01-01", end="2024-01-31")
|
|
23
|
+
|
|
24
|
+
for row in resp.data:
|
|
25
|
+
print(row.date, row.daily_min_temp, row.daily_max_temp, row.daily_total_rain)
|
|
26
|
+
|
|
27
|
+
print("credits used:", resp.credits_used)
|
|
28
|
+
print("credits remaining:", resp.credits_remaining)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Get a key from your PastClimate account. Never put a key in source code or in a URL. Call the API from a server or a script, not from a browser: the API does not accept browser calls.
|
|
32
|
+
|
|
33
|
+
## Configuration
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
client = Client(
|
|
37
|
+
api_key="YOUR_API_KEY", # default: the PASTCLIMATE_API_KEY environment variable
|
|
38
|
+
base_url="https://api.pastclimate.com",
|
|
39
|
+
timeout=30.0, # seconds per HTTP attempt; None waits forever
|
|
40
|
+
max_retries=2, # see "Retries"
|
|
41
|
+
max_retry_after=60.0, # longest Retry-After (seconds) to sleep through
|
|
42
|
+
)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
If no key is passed and the environment variable is not set, `Client()` raises `AuthenticationError` with code `missing_key`.
|
|
46
|
+
|
|
47
|
+
Every request sends `User-Agent: pastclimate-python/<version>` and `Authorization: Bearer <key>`.
|
|
48
|
+
|
|
49
|
+
## Choosing a place
|
|
50
|
+
|
|
51
|
+
Every data method takes the place in one of two ways:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
client.get_monthly("gb/london") # a location id
|
|
55
|
+
client.get_monthly(lat=51.5, lon=-0.12, country="gb") # a point and its country
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
A point is snapped to the nearest place in that country; `resp.location.requested` shows the point you sent and the distance. Find ids with `search_locations`. Location ids and the look-up calls are free, but they still count toward your request limits.
|
|
59
|
+
|
|
60
|
+
## Responses
|
|
61
|
+
|
|
62
|
+
Every successful call returns an `ApiResponse` with:
|
|
63
|
+
|
|
64
|
+
| Attribute | Meaning |
|
|
65
|
+
|---|---|
|
|
66
|
+
| `data` | The parsed `data`: a list of rows, or one object. |
|
|
67
|
+
| `meta` | The parsed `meta`: `credits`, `credits_remaining`, `methodology_version`, plus fields for the call (such as `units`). |
|
|
68
|
+
| `location` | The place the numbers are for, or `None` for calls that are not about one place. |
|
|
69
|
+
| `credits_used` | Credits this call used. |
|
|
70
|
+
| `credits_remaining` | Credits you can still spend. |
|
|
71
|
+
| `rate_limit` | `limit`, `remaining`, `reset` from the `RateLimit-*` headers (`None` when absent). |
|
|
72
|
+
| `status_code`, `headers` | The HTTP status and the response headers (lower-case names). |
|
|
73
|
+
| `raw` | The whole decoded JSON body, including fields this SDK does not model yet. |
|
|
74
|
+
|
|
75
|
+
The SDK never computes or assumes credit costs. Read them from the response.
|
|
76
|
+
|
|
77
|
+
Fields are named exactly like the API's JSON fields. The API can add new fields at any time; the models ignore ones they do not know and `raw` keeps them.
|
|
78
|
+
|
|
79
|
+
## Methods
|
|
80
|
+
|
|
81
|
+
### `search_locations(q, *, country=None)`
|
|
82
|
+
|
|
83
|
+
Search places by the start of a name (at least 3 characters). Free.
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
resp = client.search_locations("lon", country="gb")
|
|
87
|
+
for hit in resp.data:
|
|
88
|
+
print(hit.id, hit.name, hit.population, hit.weather_available)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### `nearest_location(lat, lon, country)`
|
|
92
|
+
|
|
93
|
+
The place nearest a point, inside one country. Free.
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
resp = client.nearest_location(51.5, -0.12, "gb")
|
|
97
|
+
print(resp.data.id, resp.data.requested.distance_km)
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### `get_location(location_id)`
|
|
101
|
+
|
|
102
|
+
One place by id. Free.
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
resp = client.get_location("gb/london")
|
|
106
|
+
print(resp.data.name, resp.data.timezone, resp.data.coverage.first_year)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### `get_daily(location=None, *, start, end, lat=None, lon=None, country=None, units=None, format="json")`
|
|
110
|
+
|
|
111
|
+
Daily values from `start` to `end` inclusive. Dates can be `datetime.date` objects or `"YYYY-MM-DD"` strings.
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
resp = client.get_daily("gb/london", start="2024-01-01", end="2024-01-31", units="imperial")
|
|
115
|
+
print(resp.meta.units.temperature) # "F"
|
|
116
|
+
print(resp.data[0].daily_max_temp)
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### `get_hourly(location=None, *, date, days=None, lat=None, lon=None, country=None, units=None, format="json")`
|
|
120
|
+
|
|
121
|
+
Hourly values for `days` consecutive local days starting at `date`. How many days one call may ask for, and how far back it can go, depends on your plan; call `get_me()` to see your plan's limits.
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
resp = client.get_hourly("gb/london", date="2024-01-15", days=1)
|
|
125
|
+
for row in resp.data:
|
|
126
|
+
print(row.timestamp_utc, row.temperature, row.precipitation)
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### `get_monthly(location=None, *, lat=None, lon=None, country=None, units=None)`
|
|
130
|
+
|
|
131
|
+
One row per calendar month on file, oldest first.
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
resp = client.get_monthly("gb/london")
|
|
135
|
+
print(resp.data[-1].year, resp.data[-1].month, resp.data[-1].monthly_total_rain)
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### `get_yearly(location=None, *, lat=None, lon=None, country=None, units=None)`
|
|
139
|
+
|
|
140
|
+
One row per calendar year on file, oldest first.
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
resp = client.get_yearly("gb/london")
|
|
144
|
+
print([(r.year, r.yearly_avg_temp) for r in resp.data])
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### `get_normals(location=None, *, month=None, lat=None, lon=None, country=None, units=None)`
|
|
148
|
+
|
|
149
|
+
Climate normals: `data.monthly` and `data.day_of_year`. `month` (1 to 12) narrows both.
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
resp = client.get_normals("gb/london", month=7)
|
|
153
|
+
print(resp.data.monthly[0].avg_temp, len(resp.data.day_of_year))
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### `get_records(location=None, *, lat=None, lon=None, country=None, units=None)`
|
|
157
|
+
|
|
158
|
+
The hottest, coldest, wettest and windiest day on file.
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
resp = client.get_records("gb/london")
|
|
162
|
+
for rec in resp.data:
|
|
163
|
+
print(rec.metric, rec.value, rec.unit, rec.occurred_on)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### `get_coverage(country=None)`
|
|
167
|
+
|
|
168
|
+
Countries served, with the first year and last published day. Free.
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
resp = client.get_coverage("gb")
|
|
172
|
+
print(resp.data.countries[0].last_date)
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### `get_me()`
|
|
176
|
+
|
|
177
|
+
Your plan, credit balance and limits. Free.
|
|
178
|
+
|
|
179
|
+
```python
|
|
180
|
+
resp = client.get_me()
|
|
181
|
+
print(resp.data.plan.id, resp.meta.credits_remaining, resp.data.rate_limit.per_minute)
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
## Units
|
|
185
|
+
|
|
186
|
+
`units="metric"` (the default) or `units="imperial"` on every data method. Field names do not change; the unit of each value is in `meta.units`.
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
resp = client.get_records("gb/london", units="imperial")
|
|
190
|
+
print(resp.meta.units.temperature, resp.meta.units.wind_speed) # F mph
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
## CSV
|
|
194
|
+
|
|
195
|
+
`get_daily` and `get_hourly` accept `format="csv"` and then return a `CsvResponse` instead:
|
|
196
|
+
|
|
197
|
+
```python
|
|
198
|
+
resp = client.get_daily("gb/london", start="2023-01-01", end="2023-12-31", format="csv")
|
|
199
|
+
with open("london-2023.csv", "w", newline="") as fh:
|
|
200
|
+
fh.write(resp.text)
|
|
201
|
+
print(resp.credits_used, resp.credits_remaining, resp.rate_limit.remaining)
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
CSV has no `meta`, so `credits_used` and `credits_remaining` come from the `X-Credits-*` headers. Errors are still JSON and raise the usual typed errors.
|
|
205
|
+
|
|
206
|
+
## Errors
|
|
207
|
+
|
|
208
|
+
Every error is a `PastClimateError`. Errors from an HTTP answer are `ApiError` and carry `code`, `message`, `docs_url` and `status`, plus `retry_after`, `upgrade_url`, `rate_limit` and `headers`. There is one class per category:
|
|
209
|
+
|
|
210
|
+
| Class | Codes |
|
|
211
|
+
|---|---|
|
|
212
|
+
| `AuthenticationError` | `missing_key`, `invalid_key`, `key_revoked`, `email_not_verified`, `account_suspended` |
|
|
213
|
+
| `InvalidRequestError` | `invalid_request`, `range_too_large`, `key_in_query`, `method_not_allowed`, `cors_not_supported` |
|
|
214
|
+
| `NotFoundError` | `location_not_found`, `not_published`, `location_blocked`, `not_found` |
|
|
215
|
+
| `PlanRequiredError` | `plan_required` |
|
|
216
|
+
| `RateLimitError` | `rate_limited`, `daily_request_cap_reached` |
|
|
217
|
+
| `QuotaExceededError` | `quota_exceeded` |
|
|
218
|
+
| `ServerError` | `internal_error`, `api_disabled`, `metering_unavailable` |
|
|
219
|
+
|
|
220
|
+
A code the SDK does not know yet is mapped by HTTP status, or raised as plain `ApiError`, so new codes never crash your code. `NetworkError` means no answer arrived (connection failure or timeout) after the retries ran out. A request the SDK refuses before sending (for example `get_monthly()` with no place) raises `InvalidRequestError` with `status == 0`.
|
|
221
|
+
|
|
222
|
+
```python
|
|
223
|
+
from pastclimate import (
|
|
224
|
+
Client, NotFoundError, QuotaExceededError, RateLimitError, ApiError, NetworkError,
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
client = Client()
|
|
228
|
+
try:
|
|
229
|
+
resp = client.get_daily("gb/nowhere", start="2024-01-01", end="2024-01-31")
|
|
230
|
+
except NotFoundError as err:
|
|
231
|
+
print("Unknown place or no data:", err.code, err.message)
|
|
232
|
+
except QuotaExceededError as err:
|
|
233
|
+
print("Out of credits. Upgrade here:", err.upgrade_url)
|
|
234
|
+
except RateLimitError as err:
|
|
235
|
+
print("Slow down. Try again in", err.retry_after, "seconds")
|
|
236
|
+
except ApiError as err:
|
|
237
|
+
print(err.status, err.code, err.message, err.docs_url)
|
|
238
|
+
except NetworkError as err:
|
|
239
|
+
print("Could not reach the API:", err)
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
Branch on `code`, not on `message`. Failed requests are not charged.
|
|
243
|
+
|
|
244
|
+
## Retries
|
|
245
|
+
|
|
246
|
+
The client retries automatically, up to `max_retries` times (default 2):
|
|
247
|
+
|
|
248
|
+
- **429 with a `Retry-After` header:** waits that many seconds, then retries.
|
|
249
|
+
- **5xx and network errors (including timeouts):** retries with exponential backoff and jitter.
|
|
250
|
+
- **Never retried:** every other 4xx, and a 429 without `Retry-After`. A 429 without `Retry-After` means waiting will not help, for example when the free credits are permanently used up.
|
|
251
|
+
|
|
252
|
+
If `Retry-After` is longer than `max_retry_after` (default 60 seconds), the error is raised straight away instead of sleeping, so a call never hangs for hours, for example until the daily limit resets. Read `err.retry_after` and decide for yourself. Set `max_retries=0` to turn retries off.
|
|
253
|
+
|
|
254
|
+
## Using your own HTTP library
|
|
255
|
+
|
|
256
|
+
The default transport uses only the standard library. To use `requests`, `httpx` or a test double, pass `transport`, a callable that takes an `HTTPRequest` and returns an `HTTPResponse` (status, lower-case header names, body bytes). It should raise `OSError` (for example `ConnectionError` or `TimeoutError`) when no answer arrives, and should not raise for non-2xx statuses.
|
|
257
|
+
|
|
258
|
+
```python
|
|
259
|
+
from pastclimate import Client, HTTPRequest, HTTPResponse
|
|
260
|
+
|
|
261
|
+
def transport(request: HTTPRequest) -> HTTPResponse:
|
|
262
|
+
...
|
|
263
|
+
|
|
264
|
+
client = Client("YOUR_API_KEY", transport=transport)
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## Development
|
|
268
|
+
|
|
269
|
+
```bash
|
|
270
|
+
python3 -m unittest discover -s tests -t .
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
The tests use a mocked transport, plus one file that talks to a local server on 127.0.0.1. `examples/quickstart.py` calls the live API, and only when `PASTCLIMATE_API_KEY` is set.
|
|
274
|
+
|
|
275
|
+
## License
|
|
276
|
+
|
|
277
|
+
MIT. See [LICENSE](LICENSE).
|