aiombenzin 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.
- aiombenzin-0.1.0/.github/dependabot.yml +7 -0
- aiombenzin-0.1.0/.github/workflows/ci.yml +52 -0
- aiombenzin-0.1.0/.github/workflows/release.yml +49 -0
- aiombenzin-0.1.0/.gitignore +10 -0
- aiombenzin-0.1.0/AGENTS.md +15 -0
- aiombenzin-0.1.0/CHANGELOG.md +8 -0
- aiombenzin-0.1.0/LICENSE +21 -0
- aiombenzin-0.1.0/PKG-INFO +114 -0
- aiombenzin-0.1.0/README.md +84 -0
- aiombenzin-0.1.0/pyproject.toml +54 -0
- aiombenzin-0.1.0/src/aiombenzin/__init__.py +19 -0
- aiombenzin-0.1.0/src/aiombenzin/client.py +95 -0
- aiombenzin-0.1.0/src/aiombenzin/exceptions.py +34 -0
- aiombenzin-0.1.0/src/aiombenzin/py.typed +0 -0
- aiombenzin-0.1.0/tests/test_client.py +206 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
test:
|
|
13
|
+
name: Python ${{ matrix.python }}
|
|
14
|
+
runs-on: ubuntu-latest
|
|
15
|
+
strategy:
|
|
16
|
+
fail-fast: false
|
|
17
|
+
matrix:
|
|
18
|
+
python: ["3.12", "3.13", "3.14"]
|
|
19
|
+
steps:
|
|
20
|
+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
|
21
|
+
with:
|
|
22
|
+
persist-credentials: false
|
|
23
|
+
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
|
24
|
+
with:
|
|
25
|
+
python-version: ${{ matrix.python }}
|
|
26
|
+
- name: Install
|
|
27
|
+
run: python -m pip install -e ".[test]"
|
|
28
|
+
- name: Tests (a local server; no key, no request to mBenzin.cz)
|
|
29
|
+
run: python -m pytest -q
|
|
30
|
+
- name: Typing (mypy --strict)
|
|
31
|
+
run: mypy
|
|
32
|
+
- name: Lint and format
|
|
33
|
+
run: ruff check . && ruff format --check .
|
|
34
|
+
|
|
35
|
+
build:
|
|
36
|
+
name: Build the package
|
|
37
|
+
runs-on: ubuntu-latest
|
|
38
|
+
steps:
|
|
39
|
+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
|
40
|
+
with:
|
|
41
|
+
persist-credentials: false
|
|
42
|
+
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
|
43
|
+
with:
|
|
44
|
+
python-version: "3.13"
|
|
45
|
+
- name: Build the sdist and the wheel
|
|
46
|
+
run: |
|
|
47
|
+
python -m pip install build==1.6.1
|
|
48
|
+
python -m build
|
|
49
|
+
- name: The wheel installs and imports, with its type marker
|
|
50
|
+
run: |
|
|
51
|
+
python -m pip install dist/*.whl
|
|
52
|
+
cd /tmp && python -c "import aiombenzin, importlib.resources as r; assert r.files('aiombenzin').joinpath('py.typed').is_file(); print(aiombenzin.__version__)"
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
name: Release
|
|
2
|
+
|
|
3
|
+
# Publishes to PyPI with trusted publishing (no token). Push a tag vX.Y.Z that matches pyproject.toml.
|
|
4
|
+
on:
|
|
5
|
+
push:
|
|
6
|
+
tags: ["v*"]
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
build:
|
|
13
|
+
name: Build
|
|
14
|
+
runs-on: ubuntu-latest
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
|
17
|
+
with:
|
|
18
|
+
persist-credentials: false
|
|
19
|
+
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
|
20
|
+
with:
|
|
21
|
+
python-version: "3.13"
|
|
22
|
+
- name: The tag matches the version
|
|
23
|
+
run: |
|
|
24
|
+
version=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])")
|
|
25
|
+
test "v$version" = "$GITHUB_REF_NAME"
|
|
26
|
+
- name: Build the sdist and the wheel
|
|
27
|
+
run: |
|
|
28
|
+
python -m pip install build==1.6.1
|
|
29
|
+
python -m build
|
|
30
|
+
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
|
31
|
+
with:
|
|
32
|
+
name: dist
|
|
33
|
+
path: dist/
|
|
34
|
+
|
|
35
|
+
publish:
|
|
36
|
+
name: Publish to PyPI
|
|
37
|
+
needs: build
|
|
38
|
+
runs-on: ubuntu-latest
|
|
39
|
+
environment:
|
|
40
|
+
name: pypi
|
|
41
|
+
url: https://pypi.org/p/aiombenzin
|
|
42
|
+
permissions:
|
|
43
|
+
id-token: write
|
|
44
|
+
steps:
|
|
45
|
+
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
|
46
|
+
with:
|
|
47
|
+
name: dist
|
|
48
|
+
path: dist/
|
|
49
|
+
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# AI agent instructions — aiombenzin
|
|
2
|
+
|
|
3
|
+
These instructions apply to every coding agent working in this repository.
|
|
4
|
+
|
|
5
|
+
- **aiombenzin** is the async client for the mBenzin.cz price map used by the Home Assistant integration
|
|
6
|
+
[Ceny paliv](https://github.com/Vituhlos/ha-ceny-paliv). Keep it small: downloading and errors here; caching,
|
|
7
|
+
processing and Home Assistant concerns stay in the integration.
|
|
8
|
+
- The mBenzin access key is personal. Never include a real key, token, Home Assistant configuration or other
|
|
9
|
+
personal data in code, tests, logs, issues or pull requests. Tests use a local server and a fake key.
|
|
10
|
+
- Keep the public API typed (`py.typed`, `mypy --strict`) and covered by tests; report which checks actually ran and
|
|
11
|
+
never claim validation against the live mBenzin.cz service from tests or CI.
|
|
12
|
+
- Do not merge, release (push a version tag), publish or delete branches without the maintainer's (@Vituhlos)
|
|
13
|
+
explicit authorization. Releases go to PyPI only through `.github/workflows/release.yml`.
|
|
14
|
+
- Pull requests and agent-written GitHub comments are in English and disclose AI authorship, naming the actual agent
|
|
15
|
+
and model (or `not exposed`), as in the integration's `AGENTS.md`.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- First version: `async_fetch_markers()` downloads the markers of one fuel with the caller's `aiohttp` session and
|
|
6
|
+
access key; `CannotConnect`, `InvalidAuth` and `RateLimited` (with the Retry-After delay) report failures;
|
|
7
|
+
`retry_after_seconds()`; the fuel codes in `FUELS`. Typed (`py.typed`), checked with `mypy --strict`. The code
|
|
8
|
+
comes from the Home Assistant integration Ceny paliv 0.6.2.
|
aiombenzin-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vituhlos
|
|
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,114 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: aiombenzin
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async client for the mBenzin.cz fuel price map (Czech Republic). Unofficial; needs your own access key.
|
|
5
|
+
Project-URL: Source, https://github.com/Vituhlos/aiombenzin
|
|
6
|
+
Project-URL: Issues, https://github.com/Vituhlos/aiombenzin/issues
|
|
7
|
+
Project-URL: Changelog, https://github.com/Vituhlos/aiombenzin/blob/main/CHANGELOG.md
|
|
8
|
+
Author: Vituhlos
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: asyncio,czech,fuel,home-assistant,mbenzin,prices
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Framework :: AsyncIO
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Requires-Dist: aiohttp>=3.9
|
|
24
|
+
Provides-Extra: test
|
|
25
|
+
Requires-Dist: mypy>=1.10; extra == 'test'
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
|
|
27
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
28
|
+
Requires-Dist: ruff>=0.6; extra == 'test'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# aiombenzin
|
|
32
|
+
|
|
33
|
+
Async Python client for the [mBenzin.cz](https://www.mbenzin.cz) fuel price map (Czech Republic): the prices of
|
|
34
|
+
every station for one fuel, as mBenzin.cz publishes them.
|
|
35
|
+
|
|
36
|
+
> **Unofficial.** This library is not made, endorsed or supported by mBenzin.cz. The price map is not a documented
|
|
37
|
+
> public API, and it needs a **personal access key** from mBenzin.cz: e-mail reklama@mbenzin.cz and say what you
|
|
38
|
+
> use the prices for. Never publish your key. mBenzin.cz asks that the prices are shown with the source
|
|
39
|
+
> **„Ceny: mbenzin.cz“**.
|
|
40
|
+
|
|
41
|
+
It is used by the Home Assistant integration [Ceny paliv](https://github.com/Vituhlos/ha-ceny-paliv).
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install aiombenzin
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Python 3.12 or newer, with `aiohttp`.
|
|
50
|
+
|
|
51
|
+
## Use
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import asyncio
|
|
55
|
+
|
|
56
|
+
import aiohttp
|
|
57
|
+
|
|
58
|
+
from aiombenzin import CannotConnect, InvalidAuth, RateLimited, async_fetch_markers
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
async def main() -> None:
|
|
62
|
+
async with aiohttp.ClientSession() as session: # bring your own session
|
|
63
|
+
try:
|
|
64
|
+
markers = await async_fetch_markers(session, "YOUR-KEY", "n95")
|
|
65
|
+
except RateLimited as err:
|
|
66
|
+
print(f"Too many requests; try again in {err.retry_after} s")
|
|
67
|
+
return
|
|
68
|
+
except InvalidAuth:
|
|
69
|
+
print("mBenzin.cz does not accept the key")
|
|
70
|
+
return
|
|
71
|
+
except CannotConnect as err:
|
|
72
|
+
print(f"mBenzin.cz cannot be reached: {err}")
|
|
73
|
+
return
|
|
74
|
+
cheapest = min(markers, key=lambda m: m["price"])
|
|
75
|
+
print(cheapest["name"], cheapest["addr"], cheapest["price"])
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
asyncio.run(main())
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
- **Fuels** (`aiombenzin.FUELS`): `n95` (Natural 95), `benzinplus` (Natural 98), `diesel`, `dieselplus`, `lpg`, `cng`
|
|
82
|
+
(per kg), `adblue`.
|
|
83
|
+
- **Markers** are returned as mBenzin.cz sends them, not validated. A marker usually has `id`, `url` (the station's
|
|
84
|
+
page), `name`, `chain`, `addr` (for example `Selbská 15/2732, Aš`), `price` (CZK), `fresh` (when the price was
|
|
85
|
+
updated: `Dnes`, `Včera` or a date such as `12.11.2026`), `lat`, `lng` and `ccs`.
|
|
86
|
+
- **The key** is sent in a header, never in the URL.
|
|
87
|
+
- **Errors**: `RateLimited` (HTTP 429, with `retry_after` in seconds from the Retry-After header, at most 24 hours),
|
|
88
|
+
`InvalidAuth` (HTTP 401/403 with `definite=True`, or an answer without markers, which is how mBenzin.cz answers a
|
|
89
|
+
key it does not accept), `CannotConnect` (anything else). All derive from `MBenzinError`.
|
|
90
|
+
- Options of `async_fetch_markers`: `user_agent`, `timeout` (seconds, default 60), `clock` (the current time, for an
|
|
91
|
+
HTTP-date Retry-After) and `url`.
|
|
92
|
+
|
|
93
|
+
Be gentle: one request per fuel downloads the whole country, so a few requests a day are enough.
|
|
94
|
+
|
|
95
|
+
## Development
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
pip install -e ".[test]"
|
|
99
|
+
pytest
|
|
100
|
+
ruff check . && ruff format --check .
|
|
101
|
+
mypy
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
The tests run against a local server; no key is needed and no request reaches mBenzin.cz.
|
|
105
|
+
|
|
106
|
+
## Releasing
|
|
107
|
+
|
|
108
|
+
Releases are published to PyPI by `.github/workflows/release.yml` with trusted publishing (no token): push a tag
|
|
109
|
+
`vX.Y.Z` that matches the version in `pyproject.toml`. The PyPI project trusts the workflow `release.yml` of this
|
|
110
|
+
repository in the environment `pypi`.
|
|
111
|
+
|
|
112
|
+
## License
|
|
113
|
+
|
|
114
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# aiombenzin
|
|
2
|
+
|
|
3
|
+
Async Python client for the [mBenzin.cz](https://www.mbenzin.cz) fuel price map (Czech Republic): the prices of
|
|
4
|
+
every station for one fuel, as mBenzin.cz publishes them.
|
|
5
|
+
|
|
6
|
+
> **Unofficial.** This library is not made, endorsed or supported by mBenzin.cz. The price map is not a documented
|
|
7
|
+
> public API, and it needs a **personal access key** from mBenzin.cz: e-mail reklama@mbenzin.cz and say what you
|
|
8
|
+
> use the prices for. Never publish your key. mBenzin.cz asks that the prices are shown with the source
|
|
9
|
+
> **„Ceny: mbenzin.cz“**.
|
|
10
|
+
|
|
11
|
+
It is used by the Home Assistant integration [Ceny paliv](https://github.com/Vituhlos/ha-ceny-paliv).
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install aiombenzin
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Python 3.12 or newer, with `aiohttp`.
|
|
20
|
+
|
|
21
|
+
## Use
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import asyncio
|
|
25
|
+
|
|
26
|
+
import aiohttp
|
|
27
|
+
|
|
28
|
+
from aiombenzin import CannotConnect, InvalidAuth, RateLimited, async_fetch_markers
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def main() -> None:
|
|
32
|
+
async with aiohttp.ClientSession() as session: # bring your own session
|
|
33
|
+
try:
|
|
34
|
+
markers = await async_fetch_markers(session, "YOUR-KEY", "n95")
|
|
35
|
+
except RateLimited as err:
|
|
36
|
+
print(f"Too many requests; try again in {err.retry_after} s")
|
|
37
|
+
return
|
|
38
|
+
except InvalidAuth:
|
|
39
|
+
print("mBenzin.cz does not accept the key")
|
|
40
|
+
return
|
|
41
|
+
except CannotConnect as err:
|
|
42
|
+
print(f"mBenzin.cz cannot be reached: {err}")
|
|
43
|
+
return
|
|
44
|
+
cheapest = min(markers, key=lambda m: m["price"])
|
|
45
|
+
print(cheapest["name"], cheapest["addr"], cheapest["price"])
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
asyncio.run(main())
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
- **Fuels** (`aiombenzin.FUELS`): `n95` (Natural 95), `benzinplus` (Natural 98), `diesel`, `dieselplus`, `lpg`, `cng`
|
|
52
|
+
(per kg), `adblue`.
|
|
53
|
+
- **Markers** are returned as mBenzin.cz sends them, not validated. A marker usually has `id`, `url` (the station's
|
|
54
|
+
page), `name`, `chain`, `addr` (for example `Selbská 15/2732, Aš`), `price` (CZK), `fresh` (when the price was
|
|
55
|
+
updated: `Dnes`, `Včera` or a date such as `12.11.2026`), `lat`, `lng` and `ccs`.
|
|
56
|
+
- **The key** is sent in a header, never in the URL.
|
|
57
|
+
- **Errors**: `RateLimited` (HTTP 429, with `retry_after` in seconds from the Retry-After header, at most 24 hours),
|
|
58
|
+
`InvalidAuth` (HTTP 401/403 with `definite=True`, or an answer without markers, which is how mBenzin.cz answers a
|
|
59
|
+
key it does not accept), `CannotConnect` (anything else). All derive from `MBenzinError`.
|
|
60
|
+
- Options of `async_fetch_markers`: `user_agent`, `timeout` (seconds, default 60), `clock` (the current time, for an
|
|
61
|
+
HTTP-date Retry-After) and `url`.
|
|
62
|
+
|
|
63
|
+
Be gentle: one request per fuel downloads the whole country, so a few requests a day are enough.
|
|
64
|
+
|
|
65
|
+
## Development
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
pip install -e ".[test]"
|
|
69
|
+
pytest
|
|
70
|
+
ruff check . && ruff format --check .
|
|
71
|
+
mypy
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
The tests run against a local server; no key is needed and no request reaches mBenzin.cz.
|
|
75
|
+
|
|
76
|
+
## Releasing
|
|
77
|
+
|
|
78
|
+
Releases are published to PyPI by `.github/workflows/release.yml` with trusted publishing (no token): push a tag
|
|
79
|
+
`vX.Y.Z` that matches the version in `pyproject.toml`. The PyPI project trusts the workflow `release.yml` of this
|
|
80
|
+
repository in the environment `pypi`.
|
|
81
|
+
|
|
82
|
+
## License
|
|
83
|
+
|
|
84
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "aiombenzin"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Async client for the mBenzin.cz fuel price map (Czech Republic). Unofficial; needs your own access key."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.12"
|
|
13
|
+
authors = [{ name = "Vituhlos" }]
|
|
14
|
+
keywords = ["mbenzin", "fuel", "prices", "czech", "asyncio", "home-assistant"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Framework :: AsyncIO",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Programming Language :: Python :: 3.14",
|
|
24
|
+
"Topic :: Software Development :: Libraries",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
dependencies = ["aiohttp>=3.9"]
|
|
28
|
+
|
|
29
|
+
[project.optional-dependencies]
|
|
30
|
+
test = ["pytest>=8", "pytest-asyncio>=0.24", "mypy>=1.10", "ruff>=0.6"]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Source = "https://github.com/Vituhlos/aiombenzin"
|
|
34
|
+
Issues = "https://github.com/Vituhlos/aiombenzin/issues"
|
|
35
|
+
Changelog = "https://github.com/Vituhlos/aiombenzin/blob/main/CHANGELOG.md"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.wheel]
|
|
38
|
+
packages = ["src/aiombenzin"]
|
|
39
|
+
|
|
40
|
+
[tool.pytest.ini_options]
|
|
41
|
+
asyncio_mode = "auto"
|
|
42
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
43
|
+
testpaths = ["tests"]
|
|
44
|
+
|
|
45
|
+
[tool.mypy]
|
|
46
|
+
strict = true
|
|
47
|
+
files = ["src", "tests"]
|
|
48
|
+
|
|
49
|
+
[tool.ruff]
|
|
50
|
+
line-length = 120
|
|
51
|
+
target-version = "py312"
|
|
52
|
+
|
|
53
|
+
[tool.ruff.lint]
|
|
54
|
+
select = ["E", "F", "B", "I", "UP"]
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Async client for the mBenzin.cz fuel price map (Czech Republic). Unofficial; needs your own access key."""
|
|
2
|
+
|
|
3
|
+
from .client import DEFAULT_USER_AGENT, FUELS, MAX_RETRY_AFTER, URL, async_fetch_markers, retry_after_seconds
|
|
4
|
+
from .exceptions import CannotConnect, InvalidAuth, MBenzinError, RateLimited
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"DEFAULT_USER_AGENT",
|
|
10
|
+
"FUELS",
|
|
11
|
+
"MAX_RETRY_AFTER",
|
|
12
|
+
"URL",
|
|
13
|
+
"CannotConnect",
|
|
14
|
+
"InvalidAuth",
|
|
15
|
+
"MBenzinError",
|
|
16
|
+
"RateLimited",
|
|
17
|
+
"async_fetch_markers",
|
|
18
|
+
"retry_after_seconds",
|
|
19
|
+
]
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Download the price-map markers of mBenzin.cz."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from datetime import UTC, datetime, timedelta
|
|
8
|
+
from email.utils import parsedate_to_datetime
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import aiohttp
|
|
12
|
+
|
|
13
|
+
from .exceptions import CannotConnect, InvalidAuth, RateLimited
|
|
14
|
+
|
|
15
|
+
URL = "https://www.mbenzin.cz/Mapa-cen/data"
|
|
16
|
+
DEFAULT_USER_AGENT = "aiombenzin"
|
|
17
|
+
# The fuel codes of the price map: Natural 95, Natural 98, Diesel, Diesel Plus, LPG, CNG (per kg), AdBlue.
|
|
18
|
+
FUELS: tuple[str, ...] = ("n95", "benzinplus", "diesel", "dieselplus", "lpg", "cng", "adblue")
|
|
19
|
+
# A broken or hostile Retry-After header must not block a key for longer than this.
|
|
20
|
+
MAX_RETRY_AFTER = timedelta(hours=24)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def retry_after_seconds(value: str | None, now: datetime | None = None) -> float | None:
|
|
24
|
+
"""The delay a Retry-After header asks for, in seconds (0 to 24 hours), or None when it is missing or invalid.
|
|
25
|
+
|
|
26
|
+
Both forms are understood: a number of seconds, and an HTTP date (compared with `now`, default the current
|
|
27
|
+
time in UTC).
|
|
28
|
+
"""
|
|
29
|
+
if not value:
|
|
30
|
+
return None
|
|
31
|
+
value = value.strip()
|
|
32
|
+
if value.isdecimal():
|
|
33
|
+
try:
|
|
34
|
+
delay = float(int(value))
|
|
35
|
+
except (OverflowError, ValueError):
|
|
36
|
+
return None
|
|
37
|
+
return min(delay, MAX_RETRY_AFTER.total_seconds()) if math.isfinite(delay) else None
|
|
38
|
+
try:
|
|
39
|
+
retry_at = parsedate_to_datetime(value)
|
|
40
|
+
if retry_at.tzinfo is None:
|
|
41
|
+
retry_at = retry_at.replace(tzinfo=UTC)
|
|
42
|
+
current = now or datetime.now(UTC)
|
|
43
|
+
if current.tzinfo is None:
|
|
44
|
+
current = current.replace(tzinfo=UTC)
|
|
45
|
+
delay = (retry_at - current.astimezone(UTC)).total_seconds()
|
|
46
|
+
return min(max(0.0, delay), MAX_RETRY_AFTER.total_seconds())
|
|
47
|
+
except (TypeError, ValueError, OverflowError):
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
async def async_fetch_markers(
|
|
52
|
+
session: aiohttp.ClientSession,
|
|
53
|
+
key: str,
|
|
54
|
+
fuel: str,
|
|
55
|
+
*,
|
|
56
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
57
|
+
timeout: float = 60,
|
|
58
|
+
clock: Callable[[], datetime] | None = None,
|
|
59
|
+
url: str = URL,
|
|
60
|
+
) -> list[dict[str, Any]]:
|
|
61
|
+
"""Download the markers of one fuel for the whole Czech Republic.
|
|
62
|
+
|
|
63
|
+
The caller owns `session` (Home Assistant passes its shared one) and its own access `key`, which is sent in a
|
|
64
|
+
header, never in the URL. The markers are returned as mBenzin.cz sends them, not validated: each usually has
|
|
65
|
+
`id`, `url`, `name`, `chain`, `addr`, `price`, `fresh`, `lat`, `lng` and `ccs`. `clock` gives the current
|
|
66
|
+
time for an HTTP-date Retry-After header.
|
|
67
|
+
|
|
68
|
+
Raises RateLimited (HTTP 429), InvalidAuth (HTTP 401/403, a key that cannot be sent, or an answer without
|
|
69
|
+
markers, which is what mBenzin.cz gives a key it does not accept) and CannotConnect (any other failure).
|
|
70
|
+
"""
|
|
71
|
+
try:
|
|
72
|
+
async with session.get(
|
|
73
|
+
url,
|
|
74
|
+
params={"fuel": fuel, "ccs": "0"},
|
|
75
|
+
headers={"User-Agent": user_agent, "X-Mbenzin-Klic": key},
|
|
76
|
+
timeout=aiohttp.ClientTimeout(total=timeout),
|
|
77
|
+
) as resp:
|
|
78
|
+
if resp.status == 429:
|
|
79
|
+
raise RateLimited(retry_after_seconds(resp.headers.get("Retry-After"), clock() if clock else None))
|
|
80
|
+
if resp.status in (401, 403):
|
|
81
|
+
raise InvalidAuth(definite=True)
|
|
82
|
+
if resp.status != 200:
|
|
83
|
+
raise CannotConnect(f"HTTP {resp.status}")
|
|
84
|
+
try:
|
|
85
|
+
data = await resp.json(content_type=None)
|
|
86
|
+
except ValueError: # an HTML "browser check" page: the key is not accepted
|
|
87
|
+
data = None
|
|
88
|
+
except (aiohttp.ClientError, TimeoutError) as err:
|
|
89
|
+
raise CannotConnect(type(err).__name__) from None
|
|
90
|
+
except ValueError: # aiohttp refuses a header value with control characters: not a usable key
|
|
91
|
+
raise InvalidAuth from None
|
|
92
|
+
markers = data.get("markers") if isinstance(data, dict) else None
|
|
93
|
+
if not isinstance(markers, list):
|
|
94
|
+
raise InvalidAuth
|
|
95
|
+
return markers
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Errors raised by aiombenzin."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class MBenzinError(Exception):
|
|
7
|
+
"""Base class of every aiombenzin error."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CannotConnect(MBenzinError):
|
|
11
|
+
"""mBenzin.cz cannot be reached or answered with an unexpected HTTP status."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class InvalidAuth(MBenzinError):
|
|
15
|
+
"""The access key is missing, wrong or not accepted.
|
|
16
|
+
|
|
17
|
+
`definite` is True for HTTP 401/403. mBenzin.cz also answers a key it does not accept with an HTML page, but
|
|
18
|
+
such a page can come from an outage too: callers may want to trust it only when it repeats.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(self, *args: object, definite: bool = False) -> None:
|
|
22
|
+
super().__init__(*args)
|
|
23
|
+
self.definite = definite
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class RateLimited(MBenzinError):
|
|
27
|
+
"""HTTP 429: mBenzin.cz is temporarily limiting requests.
|
|
28
|
+
|
|
29
|
+
`retry_after` is the delay in seconds from the Retry-After header (at most 24 hours), or None without one.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, retry_after: float | None = None) -> None:
|
|
33
|
+
super().__init__()
|
|
34
|
+
self.retry_after = retry_after
|
|
File without changes
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""aiombenzin against a local test server: no request ever reaches mBenzin.cz."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
|
|
9
|
+
import aiohttp
|
|
10
|
+
import pytest
|
|
11
|
+
from aiohttp import web
|
|
12
|
+
from aiohttp.test_utils import TestServer
|
|
13
|
+
|
|
14
|
+
from aiombenzin import (
|
|
15
|
+
DEFAULT_USER_AGENT,
|
|
16
|
+
FUELS,
|
|
17
|
+
URL,
|
|
18
|
+
CannotConnect,
|
|
19
|
+
InvalidAuth,
|
|
20
|
+
MBenzinError,
|
|
21
|
+
RateLimited,
|
|
22
|
+
async_fetch_markers,
|
|
23
|
+
retry_after_seconds,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
KEY = "test-key"
|
|
27
|
+
MARKER = {
|
|
28
|
+
"id": "17266",
|
|
29
|
+
"url": "/Ceny-benzinu-a-nafty/As/F1-Gas-Selbska-152732/17266",
|
|
30
|
+
"name": "F1 Gas",
|
|
31
|
+
"chain": "F1 Gas",
|
|
32
|
+
"addr": "Selbská 15/2732, Aš",
|
|
33
|
+
"price": 39.7,
|
|
34
|
+
"fresh": "12.11.2026",
|
|
35
|
+
"lat": 50.21787,
|
|
36
|
+
"lng": 12.176793,
|
|
37
|
+
"ccs": True,
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
Handler = Callable[[web.Request], Awaitable[web.StreamResponse]]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@pytest.fixture
|
|
44
|
+
async def serve() -> AsyncIterator[Callable[[Handler], Awaitable[str]]]:
|
|
45
|
+
"""Start a local server answering with `handler`; return the URL to fetch."""
|
|
46
|
+
servers: list[TestServer] = []
|
|
47
|
+
|
|
48
|
+
async def start(handler: Handler) -> str:
|
|
49
|
+
app = web.Application()
|
|
50
|
+
app.router.add_get("/Mapa-cen/data", handler)
|
|
51
|
+
server = TestServer(app)
|
|
52
|
+
await server.start_server()
|
|
53
|
+
servers.append(server)
|
|
54
|
+
return str(server.make_url("/Mapa-cen/data"))
|
|
55
|
+
|
|
56
|
+
yield start
|
|
57
|
+
for server in servers:
|
|
58
|
+
await server.close()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
async def test_markers_are_returned_and_the_key_stays_out_of_the_url(
|
|
62
|
+
serve: Callable[[Handler], Awaitable[str]],
|
|
63
|
+
) -> None:
|
|
64
|
+
seen: list[web.Request] = []
|
|
65
|
+
|
|
66
|
+
async def handler(request: web.Request) -> web.StreamResponse:
|
|
67
|
+
seen.append(request)
|
|
68
|
+
return web.json_response({"markers": [MARKER]})
|
|
69
|
+
|
|
70
|
+
url = await serve(handler)
|
|
71
|
+
async with aiohttp.ClientSession() as session:
|
|
72
|
+
markers = await async_fetch_markers(session, KEY, "n95", url=url)
|
|
73
|
+
assert markers == [MARKER]
|
|
74
|
+
request = seen[0]
|
|
75
|
+
assert request.headers["X-Mbenzin-Klic"] == KEY
|
|
76
|
+
assert request.headers["User-Agent"] == DEFAULT_USER_AGENT
|
|
77
|
+
assert dict(request.query) == {"fuel": "n95", "ccs": "0"}
|
|
78
|
+
assert KEY not in str(request.url)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def test_a_custom_user_agent_is_sent(serve: Callable[[Handler], Awaitable[str]]) -> None:
|
|
82
|
+
agents: list[str] = []
|
|
83
|
+
|
|
84
|
+
async def handler(request: web.Request) -> web.StreamResponse:
|
|
85
|
+
agents.append(request.headers["User-Agent"])
|
|
86
|
+
return web.json_response({"markers": []})
|
|
87
|
+
|
|
88
|
+
url = await serve(handler)
|
|
89
|
+
async with aiohttp.ClientSession() as session:
|
|
90
|
+
assert await async_fetch_markers(session, KEY, "lpg", url=url, user_agent="HomeAssistant-ceny-paliv") == []
|
|
91
|
+
assert agents == ["HomeAssistant-ceny-paliv"]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@pytest.mark.parametrize("status", [401, 403])
|
|
95
|
+
async def test_a_refused_key_is_definite(serve: Callable[[Handler], Awaitable[str]], status: int) -> None:
|
|
96
|
+
async def handler(request: web.Request) -> web.StreamResponse:
|
|
97
|
+
return web.Response(status=status)
|
|
98
|
+
|
|
99
|
+
url = await serve(handler)
|
|
100
|
+
async with aiohttp.ClientSession() as session:
|
|
101
|
+
with pytest.raises(InvalidAuth) as err:
|
|
102
|
+
await async_fetch_markers(session, KEY, "n95", url=url)
|
|
103
|
+
assert err.value.definite is True
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@pytest.mark.parametrize(
|
|
107
|
+
"body",
|
|
108
|
+
[
|
|
109
|
+
"<html><body>Browser check</body></html>", # what mBenzin.cz answers a key it does not accept
|
|
110
|
+
'{"error": "no markers"}',
|
|
111
|
+
'{"markers": "not a list"}',
|
|
112
|
+
"[]",
|
|
113
|
+
],
|
|
114
|
+
)
|
|
115
|
+
async def test_an_answer_without_markers_is_an_unaccepted_key(
|
|
116
|
+
serve: Callable[[Handler], Awaitable[str]], body: str
|
|
117
|
+
) -> None:
|
|
118
|
+
async def handler(request: web.Request) -> web.StreamResponse:
|
|
119
|
+
return web.Response(text=body, content_type="text/html")
|
|
120
|
+
|
|
121
|
+
url = await serve(handler)
|
|
122
|
+
async with aiohttp.ClientSession() as session:
|
|
123
|
+
with pytest.raises(InvalidAuth) as err:
|
|
124
|
+
await async_fetch_markers(session, KEY, "n95", url=url)
|
|
125
|
+
assert err.value.definite is False
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
async def test_a_key_that_cannot_be_sent_is_refused_without_a_request(
|
|
129
|
+
serve: Callable[[Handler], Awaitable[str]],
|
|
130
|
+
) -> None:
|
|
131
|
+
calls: list[web.Request] = []
|
|
132
|
+
|
|
133
|
+
async def handler(request: web.Request) -> web.StreamResponse:
|
|
134
|
+
calls.append(request)
|
|
135
|
+
return web.json_response({"markers": []})
|
|
136
|
+
|
|
137
|
+
url = await serve(handler)
|
|
138
|
+
async with aiohttp.ClientSession() as session:
|
|
139
|
+
with pytest.raises(InvalidAuth):
|
|
140
|
+
await async_fetch_markers(session, "key\nwith a line break", "n95", url=url)
|
|
141
|
+
assert calls == []
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@pytest.mark.parametrize(
|
|
145
|
+
("header", "expected"),
|
|
146
|
+
[("120", 120.0), ("999999", 86400.0), ("Sat, 14 Nov 2026 10:05:00 GMT", 300.0), ("soon", None), (None, None)],
|
|
147
|
+
)
|
|
148
|
+
async def test_rate_limiting_tells_how_long_to_wait(
|
|
149
|
+
serve: Callable[[Handler], Awaitable[str]], header: str | None, expected: float | None
|
|
150
|
+
) -> None:
|
|
151
|
+
async def handler(request: web.Request) -> web.StreamResponse:
|
|
152
|
+
return web.Response(status=429, headers={"Retry-After": header} if header else {})
|
|
153
|
+
|
|
154
|
+
url = await serve(handler)
|
|
155
|
+
async with aiohttp.ClientSession() as session:
|
|
156
|
+
with pytest.raises(RateLimited) as err:
|
|
157
|
+
await async_fetch_markers(
|
|
158
|
+
session, KEY, "diesel", url=url, clock=lambda: datetime(2026, 11, 14, 10, 0, tzinfo=UTC)
|
|
159
|
+
)
|
|
160
|
+
assert err.value.retry_after == expected
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
async def test_other_answers_and_failures_cannot_connect(serve: Callable[[Handler], Awaitable[str]]) -> None:
|
|
164
|
+
async def broken(request: web.Request) -> web.StreamResponse:
|
|
165
|
+
return web.Response(status=503)
|
|
166
|
+
|
|
167
|
+
async def slow(request: web.Request) -> web.StreamResponse:
|
|
168
|
+
await asyncio.sleep(1)
|
|
169
|
+
return web.json_response({"markers": []})
|
|
170
|
+
|
|
171
|
+
async with aiohttp.ClientSession() as session:
|
|
172
|
+
with pytest.raises(CannotConnect, match="HTTP 503"):
|
|
173
|
+
await async_fetch_markers(session, KEY, "n95", url=await serve(broken))
|
|
174
|
+
with pytest.raises(CannotConnect, match="TimeoutError"):
|
|
175
|
+
await async_fetch_markers(session, KEY, "n95", url=await serve(slow), timeout=0.05)
|
|
176
|
+
# nothing listens on this port
|
|
177
|
+
with pytest.raises(CannotConnect, match="ClientConnectorError"):
|
|
178
|
+
await async_fetch_markers(session, KEY, "n95", url="http://127.0.0.1:9/Mapa-cen/data")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def test_retry_after_parsing() -> None:
|
|
182
|
+
now = datetime(2026, 11, 14, 10, 0, tzinfo=UTC)
|
|
183
|
+
assert retry_after_seconds(" 60 ", now) == 60.0
|
|
184
|
+
assert retry_after_seconds("Sat, 14 Nov 2026 09:00:00 GMT", now) == 0.0 # already past
|
|
185
|
+
assert retry_after_seconds("Sat, 14 Nov 2026 10:01:00", now) == 60.0 # no zone: UTC
|
|
186
|
+
assert retry_after_seconds("Sat, 14 Nov 2026 10:01:00 GMT", datetime(2026, 11, 14, 10, 0)) == 60.0
|
|
187
|
+
assert retry_after_seconds("", now) is None
|
|
188
|
+
assert retry_after_seconds("9" * 400, now) is None # too large for a float
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def test_public_names() -> None:
|
|
192
|
+
assert URL == "https://www.mbenzin.cz/Mapa-cen/data"
|
|
193
|
+
assert FUELS == ("n95", "benzinplus", "diesel", "dieselplus", "lpg", "cng", "adblue")
|
|
194
|
+
assert issubclass(CannotConnect, MBenzinError)
|
|
195
|
+
assert issubclass(InvalidAuth, MBenzinError)
|
|
196
|
+
assert issubclass(RateLimited, MBenzinError)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def test_the_version_matches_the_package_metadata() -> None:
|
|
200
|
+
import tomllib
|
|
201
|
+
from pathlib import Path
|
|
202
|
+
|
|
203
|
+
import aiombenzin
|
|
204
|
+
|
|
205
|
+
pyproject = tomllib.loads((Path(__file__).parents[1] / "pyproject.toml").read_text("utf-8"))
|
|
206
|
+
assert aiombenzin.__version__ == pyproject["project"]["version"]
|