python-fuelprice 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fuelprice/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """Malaysia weekly fuel prices async client and parser."""
2
+ from __future__ import annotations
3
+
4
+ from .client import FuelPriceClient
5
+ from .const import API_PARAMS, API_URL, DEFAULT_FUEL_TYPES, FUEL_TYPES
6
+ from .exceptions import FuelPriceConnectionError, FuelPriceError
7
+ from .models import FuelPriceData, parse_fuel_prices
8
+
9
+ __all__ = [
10
+ "API_PARAMS",
11
+ "API_URL",
12
+ "DEFAULT_FUEL_TYPES",
13
+ "FUEL_TYPES",
14
+ "FuelPriceClient",
15
+ "FuelPriceConnectionError",
16
+ "FuelPriceData",
17
+ "FuelPriceError",
18
+ "parse_fuel_prices",
19
+ ]
fuelprice/client.py ADDED
@@ -0,0 +1,49 @@
1
+ """Async client for Malaysia Fuel Price (data.gov.my)."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+
6
+ import aiohttp
7
+
8
+ from .const import API_PARAMS, API_URL, REQUEST_TIMEOUT
9
+ from .exceptions import FuelPriceConnectionError, FuelPriceError
10
+ from .models import FuelPriceData, parse_fuel_prices
11
+
12
+
13
+ class FuelPriceClient:
14
+ """Async client for data.gov.my fuelprice endpoint."""
15
+
16
+ def __init__(
17
+ self,
18
+ session: aiohttp.ClientSession | None = None,
19
+ timeout: int = REQUEST_TIMEOUT,
20
+ ) -> None:
21
+ """Initialize FuelPriceClient."""
22
+ self._session = session
23
+ self._timeout = timeout
24
+
25
+ async def _get_session(self) -> aiohttp.ClientSession:
26
+ if self._session is None or self._session.closed:
27
+ self._session = aiohttp.ClientSession()
28
+ return self._session
29
+
30
+ async def async_get_latest(self) -> FuelPriceData:
31
+ """Fetch and parse the latest weekly fuel prices."""
32
+ session = await self._get_session()
33
+ try:
34
+ async with asyncio.timeout(self._timeout):
35
+ async with session.get(API_URL, params=API_PARAMS) as resp:
36
+ if resp.status != 200:
37
+ raise FuelPriceConnectionError(f"{API_URL} returned HTTP {resp.status}")
38
+ data = await resp.json(content_type=None)
39
+ except (aiohttp.ClientError, TimeoutError) as err:
40
+ raise FuelPriceConnectionError(
41
+ f"Error communicating with {API_URL}: {err}"
42
+ ) from err
43
+ except ValueError as err:
44
+ raise FuelPriceError(f"Invalid JSON from {API_URL}: {err}") from err
45
+
46
+ if not isinstance(data, list):
47
+ raise FuelPriceError(f"Unexpected payload from {API_URL}")
48
+
49
+ return parse_fuel_prices(data)
fuelprice/const.py ADDED
@@ -0,0 +1,30 @@
1
+ """Constants for python-fuelprice."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Final
5
+
6
+ API_URL: Final = "https://api.data.gov.my/data-catalogue"
7
+ API_PARAMS: Final[dict[str, str]] = {
8
+ "id": "fuelprice",
9
+ "sort": "-date",
10
+ "limit": "4",
11
+ }
12
+ REQUEST_TIMEOUT: Final = 15
13
+
14
+ FUEL_TYPES: Final[dict[str, str]] = {
15
+ "ron95": "RON95 (Market)",
16
+ "ron95_budi95": "RON95 (BUDI95)",
17
+ "ron95_skps": "RON95 (SKPS)",
18
+ "ron97": "RON97",
19
+ "diesel": "Diesel (Peninsular)",
20
+ "diesel_eastmsia": "Diesel (East Malaysia)",
21
+ "diesel_budi": "Diesel (BUDI)",
22
+ "diesel_skds": "Diesel (SKDS)",
23
+ }
24
+
25
+ DEFAULT_FUEL_TYPES: Final[list[str]] = [
26
+ "ron95",
27
+ "ron95_budi95",
28
+ "ron97",
29
+ "diesel",
30
+ ]
@@ -0,0 +1,10 @@
1
+ """Exceptions for python-fuelprice."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class FuelPriceError(Exception):
6
+ """Base exception for fuelprice API and parsing errors."""
7
+
8
+
9
+ class FuelPriceConnectionError(FuelPriceError):
10
+ """Raised when communicating with data.gov.my fails."""
fuelprice/models.py ADDED
@@ -0,0 +1,54 @@
1
+ """Models and parsers for python-fuelprice."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from typing import Any
6
+
7
+ from .const import FUEL_TYPES
8
+ from .exceptions import FuelPriceError
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class FuelPriceData:
13
+ """Latest weekly fuel prices and week-over-week changes."""
14
+
15
+ effective_date: str
16
+ levels: dict[str, float | None]
17
+ changes: dict[str, float | None]
18
+
19
+
20
+ def _to_float(value: Any) -> float | None:
21
+ if value is None or isinstance(value, bool):
22
+ return None
23
+ try:
24
+ return float(value)
25
+ except (TypeError, ValueError):
26
+ return None
27
+
28
+
29
+ def parse_fuel_prices(records: list[dict[str, Any]]) -> FuelPriceData:
30
+ """Parse data.gov.my fuelprice records into the latest FuelPriceData."""
31
+ if not records:
32
+ raise FuelPriceError("No fuel price records returned")
33
+
34
+ dates = [r.get("date") for r in records if isinstance(r.get("date"), str)]
35
+ if not dates:
36
+ raise FuelPriceError("No valid date found in fuel price records")
37
+
38
+ latest_date = max(dates)
39
+ levels: dict[str, float | None] = {}
40
+ changes: dict[str, float | None] = {}
41
+
42
+ for record in records:
43
+ if record.get("date") != latest_date:
44
+ continue
45
+ series_type = record.get("series_type")
46
+ if series_type == "level":
47
+ levels = {key: _to_float(record.get(key)) for key in FUEL_TYPES}
48
+ elif series_type == "change_weekly":
49
+ changes = {key: _to_float(record.get(key)) for key in FUEL_TYPES}
50
+
51
+ if not levels:
52
+ raise FuelPriceError(f"Missing price level record for {latest_date}")
53
+
54
+ return FuelPriceData(effective_date=latest_date, levels=levels, changes=changes)
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-fuelprice
3
+ Version: 0.1.0
4
+ Summary: Asynchronous Python client for Malaysia weekly fuel prices (data.gov.my / OpenDOSM)
5
+ Author: Zubir Jamal
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/zubirjamal/python-fuelprice
8
+ Project-URL: Repository, https://github.com/zubirjamal/python-fuelprice
9
+ Project-URL: Issues, https://github.com/zubirjamal/python-fuelprice/issues
10
+ Keywords: fuelprice,malaysia,ron95,ron97,diesel,datagovmy,home-assistant
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Topic :: Home Automation
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Intended Audience :: Developers
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ Requires-Dist: aiohttp>=3.9.0
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest>=8.0.0; extra == "test"
25
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
26
+
27
+ # python-fuelprice
28
+
29
+ Asynchronous Python client for Malaysia's weekly retail fuel prices from [data.gov.my](https://data.gov.my/data-catalogue/fuelprice) / OpenDOSM.
30
+
31
+ ## Installation
32
+ ```bash
33
+ pip install python-fuelprice
34
+ ```
35
+
36
+ ## Usage
37
+ ```python
38
+ import asyncio
39
+ from fuelprice import FuelPriceClient
40
+
41
+ async def main() -> None:
42
+ client = FuelPriceClient()
43
+ data = await client.async_get_latest()
44
+ print(data.effective_date, data.levels["ron95"], data.changes["ron95"])
45
+
46
+ asyncio.run(main())
47
+ ```
@@ -0,0 +1,9 @@
1
+ fuelprice/__init__.py,sha256=qSTeEowFXJNlyyNEptjp_dJ9s2_f39mcWWyg1fDC_tY,535
2
+ fuelprice/client.py,sha256=FnSqlmyl_dXg4K_nhQtPtrmhNPCRzegbU0MpC-n76E0,1791
3
+ fuelprice/const.py,sha256=LpRAZExbxBEHLdCJH76Jb2vGGPSesut5UT4OJT52aLk,716
4
+ fuelprice/exceptions.py,sha256=DHU06jpVAbZxALE0MY3u7AvyD0zBkGPgarUZMtAX7GU,282
5
+ fuelprice/models.py,sha256=B4qgH_BmlMgd2CgML_te27-KCAdgkkE7oi324Wi3hjY,1706
6
+ python_fuelprice-0.1.0.dist-info/METADATA,sha256=iHjvsczXL5L_kGXKzTrpVRnhzRnVJ7-fKWm2AqvfHQU,1644
7
+ python_fuelprice-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ python_fuelprice-0.1.0.dist-info/top_level.txt,sha256=bCHoInQGYxLch_F8btzWAaRvkJ0BuhsgqhElOkYTb98,10
9
+ python_fuelprice-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ fuelprice