python-opendata-transport 0.6.0__tar.gz → 0.6.3__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.
@@ -29,7 +29,7 @@ jobs:
29
29
 
30
30
  - name: Lint with ruff
31
31
  run: |
32
- pip install ruff
32
+ pip install ruff==0.17.5
33
33
  ruff check .
34
34
 
35
35
  - name: Run tests with hatch
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2017-2025 Fabian Affolter <fabian@affolter-engineering.ch>
3
+ Copyright (c) 2017-2026 Fabian Affolter <fabian@affolter-engineering.ch>
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: python_opendata_transport
3
- Version: 0.6.0
3
+ Version: 0.6.3
4
4
  Summary: Python API for interacting with transport.opendata.ch.
5
5
  Project-URL: Homepage, https://github.com/home-assistant-ecosystem/python-opendata-transport
6
6
  Project-URL: Download URL, https://github.com/home-assistant-ecosystem/python-opendata-transport/releases
@@ -60,7 +60,12 @@ be present in the ``unstable`` channel.
60
60
  Usage
61
61
  -----
62
62
 
63
- The file ``example.py`` contains an example about how to use this module.
63
+ The file ``example.py`` contains an example about how to use this module. To run it
64
+ directly from the repository without installing the module, use ``hatch``:
65
+
66
+ .. code:: bash
67
+
68
+ $ hatch run python example.py
64
69
 
65
70
  License
66
71
  -------
@@ -33,7 +33,12 @@ be present in the ``unstable`` channel.
33
33
  Usage
34
34
  -----
35
35
 
36
- The file ``example.py`` contains an example about how to use this module.
36
+ The file ``example.py`` contains an example about how to use this module. To run it
37
+ directly from the repository without installing the module, use ``hatch``:
38
+
39
+ .. code:: bash
40
+
41
+ $ hatch run python example.py
37
42
 
38
43
  License
39
44
  -------
@@ -0,0 +1,5 @@
1
+ # Security Policy
2
+
3
+ ## Reporting a Vulnerability
4
+
5
+ If would find a vulernability in the code base, please contact the author (mail@fabian-affolter.ch, Key: 0xE23CD2DD36A4397F, Fingerprint: 2F6C 930F D3C4 7E38 6AFA 4EB4 E23C D2DD 36A4 397F).
@@ -4,9 +4,11 @@ import asyncio
4
4
 
5
5
  import aiohttp
6
6
 
7
- from opendata_transport import OpendataTransport
8
- from opendata_transport import OpendataTransportStationboard
9
- from opendata_transport import OpendataTransportLocation
7
+ from opendata_transport import (
8
+ OpendataTransport,
9
+ OpendataTransportLocation,
10
+ OpendataTransportStationboard,
11
+ )
10
12
 
11
13
 
12
14
  async def main():
@@ -21,7 +23,7 @@ async def main():
21
23
  print(locations.locations)
22
24
 
23
25
  # Print as list
24
- print(list(map(lambda x: x["name"], locations.locations)))
26
+ print([x["name"] for x in locations.locations])
25
27
 
26
28
  # Search a station by coordinates
27
29
  locations = OpendataTransportLocation(session, x=47.2, y=8.7)
@@ -33,7 +35,7 @@ async def main():
33
35
  print(locations.locations)
34
36
 
35
37
  # Print as list
36
- print(list(map(lambda x: x["name"], locations.locations)))
38
+ print([x["name"] for x in locations.locations])
37
39
 
38
40
  print()
39
41
 
@@ -1,11 +1,10 @@
1
1
  """Wrapper to get connection details from Opendata Transport."""
2
2
 
3
- import asyncio
4
3
  import logging
4
+ import urllib.parse
5
5
  from datetime import datetime, timedelta
6
6
 
7
7
  import aiohttp
8
- import urllib.parse
9
8
 
10
9
  from . import exceptions
11
10
 
@@ -16,7 +15,7 @@ _RESOURCE_URL = "http://transport.opendata.ch/v1/"
16
15
  _DEFAULT_RATE_LIMIT_STATS_HISTORY = 7 # default 7 days
17
16
 
18
17
 
19
- class OpendataTransportBase(object):
18
+ class OpendataTransportBase:
20
19
  """Representation of the Opendata Transport base class"""
21
20
 
22
21
  def __init__(
@@ -39,13 +38,14 @@ class OpendataTransportBase(object):
39
38
  def get_url(resource, params):
40
39
  """Generate the URL for the request."""
41
40
  param = urllib.parse.urlencode(params, True)
42
- url = "{resource_url}{resource}?{param}".format(
43
- resource_url=_RESOURCE_URL, resource=resource, param=param
44
- )
41
+ url = f"{_RESOURCE_URL}{resource}?{param}"
45
42
  return url
46
43
 
47
44
  def update_stats(self, success: bool = True) -> None:
48
45
  """Update the stats and record every call."""
46
+ if not self._enable_rate_limit_stats:
47
+ return
48
+
49
49
  today = datetime.now().date()
50
50
  today_key = today.isoformat()
51
51
  keep_dates = [
@@ -134,7 +134,7 @@ class OpendataTransportLocation(OpendataTransportBase):
134
134
  data = await response.json()
135
135
  self.update_stats(success=True)
136
136
  _LOGGER.debug(data)
137
- except asyncio.TimeoutError as e:
137
+ except TimeoutError as e:
138
138
  self.update_stats(success=False)
139
139
  _LOGGER.error("Can not load data from transport.opendata.ch")
140
140
  raise exceptions.OpendataTransportConnectionError() from e
@@ -196,6 +196,17 @@ class OpendataTransportStationboard(OpendataTransportBase):
196
196
  "category": journey["category"],
197
197
  "number": journey["number"],
198
198
  "to": journey["to"],
199
+ "pass_list": [
200
+ {
201
+ "id": stop["station"]["id"],
202
+ "name": stop["station"]["name"],
203
+ "arrival": stop["arrival"],
204
+ "departure": stop["departure"],
205
+ "delay": stop["delay"],
206
+ "platform": stop["platform"],
207
+ }
208
+ for stop in journey.get("passList") or []
209
+ ],
199
210
  }
200
211
 
201
212
  async def __async_get_data(self, station):
@@ -224,7 +235,7 @@ class OpendataTransportStationboard(OpendataTransportBase):
224
235
  data = await response.json()
225
236
  self.update_stats(success=True)
226
237
  _LOGGER.debug(data)
227
- except asyncio.TimeoutError as e:
238
+ except TimeoutError as e:
228
239
  self.update_stats(success=False)
229
240
  _LOGGER.error("Can not load data from transport.opendata.ch")
230
241
  raise exceptions.OpendataTransportConnectionError() from e
@@ -291,12 +302,12 @@ class OpendataTransport(OpendataTransportBase):
291
302
 
292
303
  self.from_name = self.from_id = self.to_name = self.to_id = None
293
304
 
294
- self.connections = dict()
305
+ self.connections = {}
295
306
 
296
307
  @staticmethod
297
308
  def get_connection(connection):
298
309
  """Get the connection details."""
299
- connection_info = dict()
310
+ connection_info = {}
300
311
  connection_info["departure"] = connection["from"]["departure"]
301
312
  connection_info["duration"] = connection["duration"]
302
313
  connection_info["delay"] = connection["from"]["delay"]
@@ -346,7 +357,7 @@ class OpendataTransport(OpendataTransportBase):
346
357
  data = await response.json()
347
358
  self.update_stats(success=True)
348
359
  _LOGGER.debug(data)
349
- except asyncio.TimeoutError as e:
360
+ except TimeoutError as e:
350
361
  self.update_stats(success=False)
351
362
  _LOGGER.error("Can not load data from transport.opendata.ch")
352
363
  raise exceptions.OpendataTransportConnectionError() from e
@@ -4,10 +4,6 @@
4
4
  class OpendataTransportError(Exception):
5
5
  """General OpenDataError exception occurred."""
6
6
 
7
- pass
8
-
9
7
 
10
8
  class OpendataTransportConnectionError(OpendataTransportError):
11
9
  """When a connection error is encountered."""
12
-
13
- pass
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "python_opendata_transport"
7
- version = "0.6.0"
7
+ version = "0.6.3"
8
8
  description = "Python API for interacting with transport.opendata.ch."
9
9
  readme = "README.rst"
10
10
  license = { text = "MIT" }
@@ -42,6 +42,7 @@ dependencies = [
42
42
  "pytest-asyncio>=0.21",
43
43
  "aiohttp>=3.8.4,<4"
44
44
  ]
45
+
45
46
  [tool.hatch.envs.test.scripts]
46
47
  run = "pytest"
47
48
 
@@ -3,11 +3,11 @@
3
3
  import pytest
4
4
 
5
5
  from opendata_transport import (
6
+ OpendataTransport,
6
7
  OpendataTransportLocation,
7
8
  OpendataTransportStationboard,
8
- OpendataTransport,
9
+ exceptions,
9
10
  )
10
- from opendata_transport import exceptions
11
11
 
12
12
 
13
13
  class DummyResponse:
@@ -85,6 +85,64 @@ async def test_stationboard_success():
85
85
  stationboard = OpendataTransportStationboard("Bern", session)
86
86
  await stationboard.async_get_data()
87
87
  assert stationboard.journeys[0]["name"] == "IC 1"
88
+ assert stationboard.journeys[0]["pass_list"] == []
89
+
90
+
91
+ @pytest.mark.asyncio
92
+ async def test_stationboard_pass_list():
93
+ """Test the stops a journey passes are returned."""
94
+ dummy_json = {
95
+ "stationboard": [
96
+ {
97
+ "stop": {
98
+ "departure": "2024-01-01T12:00:00+01:00",
99
+ "delay": 0,
100
+ "platform": "1",
101
+ },
102
+ "name": "IC 1",
103
+ "category": "IC",
104
+ "number": "1",
105
+ "to": "Geneva",
106
+ "passList": [
107
+ {
108
+ "station": {"id": "8507000", "name": "Bern"},
109
+ "arrival": None,
110
+ "departure": "2024-01-01T12:00:00+01:00",
111
+ "delay": 0,
112
+ "platform": "1",
113
+ },
114
+ {
115
+ "station": {"id": "8504100", "name": "Fribourg/Freiburg"},
116
+ "arrival": "2024-01-01T12:21:00+01:00",
117
+ "departure": "2024-01-01T12:23:00+01:00",
118
+ "delay": 2,
119
+ "platform": None,
120
+ },
121
+ ],
122
+ }
123
+ ]
124
+ }
125
+ session = DummySession(DummyResponse(200, dummy_json))
126
+ stationboard = OpendataTransportStationboard("Bern", session)
127
+ await stationboard.async_get_data()
128
+ assert stationboard.journeys[0]["pass_list"] == [
129
+ {
130
+ "id": "8507000",
131
+ "name": "Bern",
132
+ "arrival": None,
133
+ "departure": "2024-01-01T12:00:00+01:00",
134
+ "delay": 0,
135
+ "platform": "1",
136
+ },
137
+ {
138
+ "id": "8504100",
139
+ "name": "Fribourg/Freiburg",
140
+ "arrival": "2024-01-01T12:21:00+01:00",
141
+ "departure": "2024-01-01T12:23:00+01:00",
142
+ "delay": 2,
143
+ "platform": None,
144
+ },
145
+ ]
88
146
 
89
147
 
90
148
  @pytest.mark.asyncio
@@ -130,3 +188,27 @@ async def test_connection_keyerror():
130
188
  connection = OpendataTransport("Bern", "Geneva", session)
131
189
  with pytest.raises(exceptions.OpendataTransportError):
132
190
  await connection.async_get_data()
191
+
192
+
193
+ @pytest.mark.asyncio
194
+ async def test_rate_limit_stats_disabled_by_default():
195
+ """Test that no stats are recorded unless enabled."""
196
+ session = DummySession(DummyResponse(200, {"stations": []}))
197
+ location = OpendataTransportLocation(session, query="Bern")
198
+ await location.async_get_data()
199
+ assert location.rate_limit_stats == {}
200
+
201
+
202
+ @pytest.mark.asyncio
203
+ async def test_rate_limit_stats_enabled():
204
+ """Test that stats are recorded when enabled."""
205
+ session = DummySession(DummyResponse(200, {"stations": []}))
206
+ location = OpendataTransportLocation(
207
+ session, query="Bern", enable_rate_limit_stats=True
208
+ )
209
+ await location.async_get_data()
210
+ await location.async_get_data()
211
+ (stats,) = location.rate_limit_stats.values()
212
+ assert stats["count"] == 2
213
+ assert stats["errors"] == 0
214
+ assert len(stats["timestamps_success"]) == 2