weiche 0.9.1__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.
- weiche/__init__.py +48 -0
- weiche/api/__init__.py +0 -0
- weiche/api/asynchronous.py +68 -0
- weiche/api/base.py +47 -0
- weiche/api/parser.py +17 -0
- weiche/api/synchronous.py +68 -0
- weiche/const.py +1 -0
- weiche/formatter.py +9 -0
- weiche/objects.py +387 -0
- weiche/schiene.py +135 -0
- weiche/tests/__init__.py +1 -0
- weiche/tests/test_asynchronous.py +25 -0
- weiche/tests/test_schiene.py +19 -0
- weiche/tests/test_synchronous.py +43 -0
- weiche/version.py +21 -0
- weiche-0.9.1.dist-info/METADATA +269 -0
- weiche-0.9.1.dist-info/RECORD +20 -0
- weiche-0.9.1.dist-info/WHEEL +5 -0
- weiche-0.9.1.dist-info/licenses/LICENSE +21 -0
- weiche-0.9.1.dist-info/top_level.txt +1 -0
weiche/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# flake8: noqa: F401
|
|
2
|
+
|
|
3
|
+
from weiche.objects import (
|
|
4
|
+
BahnCard25Reduction1stClass,
|
|
5
|
+
BahnCard25Reduction2ndClass,
|
|
6
|
+
BahnCard50Reduction1stClass,
|
|
7
|
+
BahnCard50Reduction2ndClass,
|
|
8
|
+
BahnCard100Reduction1stClass,
|
|
9
|
+
BahnCard100Reduction2ndClass,
|
|
10
|
+
BahnCardBusiness25Reduction1stClass,
|
|
11
|
+
BahnCardBusiness25Reduction2ndClass,
|
|
12
|
+
BahnCardBusiness50Reduction1stClass,
|
|
13
|
+
BahnCardBusiness50Reduction2ndClass,
|
|
14
|
+
ChGeneralAbonnementReduction1stClass,
|
|
15
|
+
ChGeneralAbonnementReduction2ndClass,
|
|
16
|
+
ChHalbtaxaboReduction,
|
|
17
|
+
Connection,
|
|
18
|
+
ConnectionRequest,
|
|
19
|
+
ConnectionSegment,
|
|
20
|
+
KlimaticketOeReduction,
|
|
21
|
+
Location,
|
|
22
|
+
NL40Reduction,
|
|
23
|
+
Priority,
|
|
24
|
+
ProductType,
|
|
25
|
+
Reduction,
|
|
26
|
+
ReductionType,
|
|
27
|
+
RequestType,
|
|
28
|
+
Traveller,
|
|
29
|
+
TravellerType,
|
|
30
|
+
VorteilsCardOesterreichReduction,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
from weiche.api.synchronous import SynchronousApi
|
|
35
|
+
except ImportError:
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
from weiche.api.asynchronous import AsynchronousApi
|
|
41
|
+
except ImportError:
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
from weiche.schiene import Schiene
|
|
47
|
+
except ImportError:
|
|
48
|
+
pass
|
weiche/api/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from http import HTTPStatus
|
|
3
|
+
|
|
4
|
+
import aiohttp
|
|
5
|
+
|
|
6
|
+
from weiche.api.base import BaseApi
|
|
7
|
+
from weiche.api.parser import parse_associations, parse_connection_response, parse_locations
|
|
8
|
+
from weiche.const import DEFAULT_BASE_URL
|
|
9
|
+
from weiche.objects import Association, Connection, ConnectionRequest, Location
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AsynchronousApi(BaseApi):
|
|
13
|
+
def __init__(self, base_url: str = DEFAULT_BASE_URL):
|
|
14
|
+
super().__init__(base_url)
|
|
15
|
+
self.session = aiohttp.ClientSession()
|
|
16
|
+
|
|
17
|
+
async def get_travel_associations(self) -> list[Association]:
|
|
18
|
+
async with self.session.get(self.travel_associations_url) as response:
|
|
19
|
+
assert response.status == HTTPStatus.OK, f"Error: {response.status}"
|
|
20
|
+
return parse_associations(await response.json())
|
|
21
|
+
|
|
22
|
+
async def search_locations(self, query: str, limit: int = 10, location_type: str = "ALL") -> list[Location]:
|
|
23
|
+
async with self.session.get(
|
|
24
|
+
self.locations_url,
|
|
25
|
+
params=self.get_locations_params(
|
|
26
|
+
query=query,
|
|
27
|
+
limit=limit,
|
|
28
|
+
location_type=location_type,
|
|
29
|
+
),
|
|
30
|
+
) as response:
|
|
31
|
+
assert response.status == HTTPStatus.OK, f"Error: {response.status}"
|
|
32
|
+
return parse_locations(await response.json())
|
|
33
|
+
|
|
34
|
+
async def search_connections(
|
|
35
|
+
self,
|
|
36
|
+
at: datetime,
|
|
37
|
+
from_location: str,
|
|
38
|
+
to_location: str,
|
|
39
|
+
limit: int = 10,
|
|
40
|
+
) -> list[Connection]:
|
|
41
|
+
return await self.search_connections_ext(
|
|
42
|
+
self.get_connections_request_from_params(from_location, to_location, at),
|
|
43
|
+
limit=limit,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
async def search_connections_ext(self, request: ConnectionRequest, limit: int = 10) -> list[Connection]:
|
|
47
|
+
responses: list[Connection] = []
|
|
48
|
+
while len(responses) < limit:
|
|
49
|
+
request_params = self.get_connections_ext_params(request)
|
|
50
|
+
async with self.session.post(
|
|
51
|
+
self.connections_url,
|
|
52
|
+
json=request_params,
|
|
53
|
+
) as response:
|
|
54
|
+
assert response.status in (
|
|
55
|
+
HTTPStatus.OK,
|
|
56
|
+
HTTPStatus.CREATED,
|
|
57
|
+
), f"Error: {response.status}, {await response.text()}"
|
|
58
|
+
connection_response = parse_connection_response(await response.json())
|
|
59
|
+
responses.extend(connection_response.connections)
|
|
60
|
+
if limit and len(responses) > limit:
|
|
61
|
+
responses = responses[:limit]
|
|
62
|
+
|
|
63
|
+
if not connection_response.has_more:
|
|
64
|
+
break
|
|
65
|
+
|
|
66
|
+
request.paging_reference = connection_response.next_pointer
|
|
67
|
+
|
|
68
|
+
return responses
|
weiche/api/base.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from typing import Any
|
|
4
|
+
from urllib.parse import urljoin
|
|
5
|
+
|
|
6
|
+
from weiche.const import DEFAULT_BASE_URL
|
|
7
|
+
from weiche.objects import ConnectionRequest
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class BaseApi:
|
|
11
|
+
def __init__(self, base_url: str = DEFAULT_BASE_URL):
|
|
12
|
+
self.base_url = base_url
|
|
13
|
+
|
|
14
|
+
@property
|
|
15
|
+
def locations_url(self):
|
|
16
|
+
return urljoin(self.base_url, "reiseloesung/orte")
|
|
17
|
+
|
|
18
|
+
def get_locations_params(self, query: str, limit: int = 10, location_type: str = "ALL") -> dict[str, Any]:
|
|
19
|
+
return {
|
|
20
|
+
"suchbegriff": query,
|
|
21
|
+
"typ": location_type,
|
|
22
|
+
"limit": limit,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def connections_url(self):
|
|
27
|
+
return urljoin(self.base_url, "angebote/fahrplan")
|
|
28
|
+
|
|
29
|
+
def get_connections_request_from_params(
|
|
30
|
+
self, from_location: str, to_location: str, at: datetime | None = None, paging_reference: str | None = None
|
|
31
|
+
) -> ConnectionRequest:
|
|
32
|
+
at = at or datetime.now()
|
|
33
|
+
return ConnectionRequest(
|
|
34
|
+
time=at,
|
|
35
|
+
origin=from_location,
|
|
36
|
+
destination=to_location,
|
|
37
|
+
paging_reference=paging_reference,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
def get_connections_ext_params(self, request: ConnectionRequest) -> dict[str, Any]:
|
|
41
|
+
request = request.model_copy()
|
|
42
|
+
request.time = request.time.replace(tzinfo=None, microsecond=0)
|
|
43
|
+
return json.loads(request.model_dump_json(by_alias=True, exclude_none=True))
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def travel_associations_url(self):
|
|
47
|
+
return urljoin(self.base_url, "angebote/stammdaten/verbuende")
|
weiche/api/parser.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from pydantic import RootModel
|
|
4
|
+
|
|
5
|
+
from weiche.objects import Association, ConnectionResponse, Location
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def parse_locations(payload: list[Any]) -> list[Location]:
|
|
9
|
+
return RootModel[list[Location]].model_validate(payload, by_alias=True).root
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def parse_connection_response(payload: dict[str, Any]) -> ConnectionResponse:
|
|
13
|
+
return ConnectionResponse.model_validate(payload, by_alias=True)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def parse_associations(payload: list[Any]) -> list[Association]:
|
|
17
|
+
return RootModel[list[Association]].model_validate(payload, by_alias=True).root
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from http import HTTPStatus
|
|
3
|
+
|
|
4
|
+
import requests
|
|
5
|
+
|
|
6
|
+
from weiche.api.base import BaseApi
|
|
7
|
+
from weiche.api.parser import parse_associations, parse_connection_response, parse_locations
|
|
8
|
+
from weiche.const import DEFAULT_BASE_URL
|
|
9
|
+
from weiche.objects import Association, Connection, ConnectionRequest, Location
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SynchronousApi(BaseApi):
|
|
13
|
+
def __init__(self, base_url: str = DEFAULT_BASE_URL):
|
|
14
|
+
super().__init__(base_url)
|
|
15
|
+
self.session = requests.Session()
|
|
16
|
+
|
|
17
|
+
def get_travel_associations(self) -> list[Association]:
|
|
18
|
+
response = self.session.get(self.travel_associations_url)
|
|
19
|
+
assert response.status_code == HTTPStatus.OK, f"Error: {response.status_code}"
|
|
20
|
+
return parse_associations(response.json())
|
|
21
|
+
|
|
22
|
+
def search_locations(self, query: str, limit: int = 10, location_type: str = "ALL") -> list[Location]:
|
|
23
|
+
response = self.session.get(
|
|
24
|
+
self.locations_url,
|
|
25
|
+
params=self.get_locations_params(
|
|
26
|
+
query=query,
|
|
27
|
+
limit=limit,
|
|
28
|
+
location_type=location_type,
|
|
29
|
+
),
|
|
30
|
+
)
|
|
31
|
+
assert response.status_code == HTTPStatus.OK, f"Error: {response.status_code}"
|
|
32
|
+
return parse_locations(response.json())
|
|
33
|
+
|
|
34
|
+
def search_connections(
|
|
35
|
+
self,
|
|
36
|
+
at: datetime,
|
|
37
|
+
from_location: str,
|
|
38
|
+
to_location: str,
|
|
39
|
+
limit: int = 10,
|
|
40
|
+
) -> list[Connection]:
|
|
41
|
+
return self.search_connections_ext(
|
|
42
|
+
self.get_connections_request_from_params(from_location, to_location, at),
|
|
43
|
+
limit=limit,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
def search_connections_ext(self, request: ConnectionRequest, limit: int = 10) -> list[Connection]:
|
|
47
|
+
responses: list[Connection] = []
|
|
48
|
+
while len(responses) < limit:
|
|
49
|
+
request_params = self.get_connections_ext_params(request)
|
|
50
|
+
response = self.session.post(
|
|
51
|
+
self.connections_url,
|
|
52
|
+
json=request_params,
|
|
53
|
+
)
|
|
54
|
+
assert response.status_code in (
|
|
55
|
+
HTTPStatus.OK,
|
|
56
|
+
HTTPStatus.CREATED,
|
|
57
|
+
), f"Error: {response.status_code}, {response.text}"
|
|
58
|
+
connection_response = parse_connection_response(response.json())
|
|
59
|
+
responses.extend(connection_response.connections)
|
|
60
|
+
if limit and len(responses) > limit:
|
|
61
|
+
responses = responses[:limit]
|
|
62
|
+
|
|
63
|
+
if not connection_response.has_more:
|
|
64
|
+
break
|
|
65
|
+
|
|
66
|
+
request.paging_reference = connection_response.next_pointer
|
|
67
|
+
|
|
68
|
+
return responses
|
weiche/const.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
DEFAULT_BASE_URL = "https://int.bahn.de/web/api/"
|
weiche/formatter.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
from datetime import timedelta
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def timedelta_to_hours_and_seconds_string(delta: timedelta) -> str:
|
|
5
|
+
"""Convert a timedelta to a string in the format HH:MM."""
|
|
6
|
+
total_seconds = int(delta.total_seconds())
|
|
7
|
+
hours, remainder = divmod(total_seconds, 3600)
|
|
8
|
+
minutes = remainder // 60
|
|
9
|
+
return f"{hours:02}:{minutes:02}"
|
weiche/objects.py
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
from datetime import date, datetime, timedelta
|
|
2
|
+
from enum import Enum
|
|
3
|
+
from typing import Any, Literal
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel as _BaseModel
|
|
6
|
+
from pydantic import ConfigDict, Field
|
|
7
|
+
|
|
8
|
+
from weiche.formatter import timedelta_to_hours_and_seconds_string
|
|
9
|
+
|
|
10
|
+
CANCELLED_MESSAGE_KEY = "text.realtime.stop.cancelled"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class BaseModel(_BaseModel):
|
|
14
|
+
model_config = ConfigDict(
|
|
15
|
+
populate_by_name=True,
|
|
16
|
+
use_enum_values=True,
|
|
17
|
+
extra="ignore",
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Location(BaseModel):
|
|
22
|
+
ext_id: str = Field(alias="extId")
|
|
23
|
+
id: str
|
|
24
|
+
lat: float
|
|
25
|
+
lon: float
|
|
26
|
+
name: str
|
|
27
|
+
type: str = Field(alias="typ")
|
|
28
|
+
products: list[str] = Field(default_factory=list)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Reference(BaseModel):
|
|
32
|
+
earlier: str | None = Field(None)
|
|
33
|
+
later: str | None = Field(None)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ConnectionSegmentNote(BaseModel):
|
|
37
|
+
key: str
|
|
38
|
+
value: str
|
|
39
|
+
route_idx_from: int | None = Field(None, alias="routeIdxFrom")
|
|
40
|
+
route_idx_to: int | None = Field(None, alias="routeIdxTo")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Priority(Enum):
|
|
44
|
+
LOW = "NIEDRIG"
|
|
45
|
+
MEDIUM = "MITTEL"
|
|
46
|
+
HIGH = "HOCH"
|
|
47
|
+
VERY_HIGH = "SEHR HOCH"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ResultSummary(BaseModel):
|
|
51
|
+
priority: Priority = Field(alias="prioritaet")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Price(BaseModel):
|
|
55
|
+
amount: float = Field(alias="betrag")
|
|
56
|
+
currency: str = Field(alias="waehrung")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class OfferPriceVat(BaseModel):
|
|
60
|
+
vat: float = Field(alias="satz")
|
|
61
|
+
literal: str | None = Field(None, alias="literal")
|
|
62
|
+
amount: Price = Field(alias="betrag")
|
|
63
|
+
with_vat: Price = Field(alias="brutto")
|
|
64
|
+
without_vat: Price = Field(alias="netto")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class OfferPrice(BaseModel):
|
|
68
|
+
amount: float = Field(alias="betrag")
|
|
69
|
+
currency: str = Field(alias="waehrung")
|
|
70
|
+
vat: list[OfferPriceVat] = Field(alias="mwst")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class ConnectionSegmentPrioritizedMessage(BaseModel):
|
|
74
|
+
|
|
75
|
+
text: str = Field(alias="text")
|
|
76
|
+
priority: Priority = Field(alias="prioritaet")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class ConnectionSegmentMessage(ConnectionSegmentPrioritizedMessage):
|
|
80
|
+
title: str = Field(alias="ueberschrift")
|
|
81
|
+
modified: datetime = Field(alias="modDateTime")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class TrainUtilization(BaseModel):
|
|
85
|
+
coach_class: str = Field(alias="klasse")
|
|
86
|
+
utilization_level: int = Field(alias="stufe")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class TrainUtilizationText(BaseModel):
|
|
90
|
+
coach_class: str = Field(alias="klasse")
|
|
91
|
+
utilization_level: int = Field(alias="stufe")
|
|
92
|
+
short_text: str = Field("", alias="kurztext")
|
|
93
|
+
display_text: str = Field("", alias="anzeigeText")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class ConnectionSegmentStop(BaseModel):
|
|
97
|
+
id: str
|
|
98
|
+
departure_time: datetime | None = Field(None, alias="abfahrtsZeitpunkt")
|
|
99
|
+
ez_departure_time: datetime | None = Field(None, alias="ezAbfahrtsZeitpunkt")
|
|
100
|
+
utilizations: list[TrainUtilization] = Field(alias="auslastungsmeldungen")
|
|
101
|
+
track: str | None = Field(None, alias="gleis")
|
|
102
|
+
stop_type: str | None = Field(None, alias="haltTyp")
|
|
103
|
+
name: str = Field(alias="name")
|
|
104
|
+
notes: list[ConnectionSegmentNote] = Field(alias="risNotizen", default_factory=list)
|
|
105
|
+
messages: list[ConnectionSegmentMessage] = Field(alias="himMeldungen", default_factory=list)
|
|
106
|
+
prioritized_messages: list[ConnectionSegmentPrioritizedMessage] = Field(alias="priorisierteMeldungen")
|
|
107
|
+
train_stop_info_id: str | None = Field(None, alias="bahnhofsInfoId")
|
|
108
|
+
ext_id: str = Field(alias="extId")
|
|
109
|
+
route_idx: int = Field(alias="routeIdx")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class MeansOfTransportAttribute(BaseModel):
|
|
113
|
+
category: str = Field(alias="kategorie")
|
|
114
|
+
key: str = Field(alias="key")
|
|
115
|
+
value: str = Field(alias="value")
|
|
116
|
+
partial_travel_information: str | None = Field(None, alias="teilstreckenHinweis")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class MeansOfTransport(BaseModel):
|
|
120
|
+
product_type: str | None = Field(None, alias="produktGattung")
|
|
121
|
+
category: str | None = Field(None, alias="kategorie")
|
|
122
|
+
name: str = Field(alias="name")
|
|
123
|
+
number: str | None = Field(None, alias="nummer")
|
|
124
|
+
direction: str | None = Field(None, alias="richtung")
|
|
125
|
+
type: str = Field(alias="typ")
|
|
126
|
+
short_text: str | None = Field(None, alias="kurzText")
|
|
127
|
+
medium_text: str | None = Field(None, alias="mittelText")
|
|
128
|
+
long_text: str | None = Field(None, alias="langText")
|
|
129
|
+
attributes: list[MeansOfTransportAttribute] = Field(alias="zugattribute", default_factory=list)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class ServiceDays(BaseModel):
|
|
133
|
+
last_date_in_period: date = Field(alias="lastDateInPeriod")
|
|
134
|
+
regular: str = Field(alias="regular")
|
|
135
|
+
irregular: str | None = Field(None, alias="irregular")
|
|
136
|
+
planning_period_begin: date = Field(alias="planningPeriodBegin")
|
|
137
|
+
planning_period_end: date = Field(alias="planningPeriodEnd")
|
|
138
|
+
weekdays: list[str] = Field(alias="weekdays")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class ConnectionSegment(BaseModel):
|
|
142
|
+
notes: list[ConnectionSegmentNote] = Field(alias="risNotizen")
|
|
143
|
+
messages: list[ConnectionSegmentMessage] = Field(alias="himMeldungen")
|
|
144
|
+
prioritized_messages: list[ConnectionSegmentPrioritizedMessage] = Field(alias="priorisierteMeldungen")
|
|
145
|
+
external_train_station_origin_id: str | None = Field(None, alias="externeBahnhofsinfoIdOrigin")
|
|
146
|
+
external_train_station_destination_id: str | None = Field(None, alias="externeBahnhofsinfoIdDestination")
|
|
147
|
+
departure_time: datetime | None = Field(None, alias="abfahrtsZeitpunkt")
|
|
148
|
+
departure_location: str = Field(alias="abfahrtsOrt")
|
|
149
|
+
departure_location_ext_id: str = Field(alias="abfahrtsOrtExtId")
|
|
150
|
+
travel_time: int = Field(alias="abschnittsDauer")
|
|
151
|
+
travel_fraction: float = Field(alias="abschnittsAnteil")
|
|
152
|
+
arrival_time: datetime = Field(alias="ankunftsZeitpunkt")
|
|
153
|
+
arrival_location: str = Field(alias="ankunftsOrt")
|
|
154
|
+
arrival_location_ext_id: str = Field(alias="ankunftsOrtExtId")
|
|
155
|
+
utilizations: list[TrainUtilization] = Field(alias="auslastungsmeldungen")
|
|
156
|
+
ez_departure_time: datetime | None = Field(None, alias="ezAbfahrtsZeitpunkt")
|
|
157
|
+
ez_arrival_time: datetime | None = Field(None, alias="ezAnkunftsZeitpunkt")
|
|
158
|
+
ez_travel_time_in_seconds: int | None = Field(None, alias="ezAbschnittsDauerInSeconds")
|
|
159
|
+
stops: list[ConnectionSegmentStop] = Field(alias="halte")
|
|
160
|
+
idx: int = Field(alias="idx")
|
|
161
|
+
means_of_transport: MeansOfTransport = Field(alias="verkehrsmittel")
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def cancelled(self) -> bool:
|
|
165
|
+
return any(note.key == CANCELLED_MESSAGE_KEY for note in self.notes)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class OfferInformation(BaseModel):
|
|
169
|
+
code: str = Field(alias="code")
|
|
170
|
+
message_short: str = Field(alias="nachrichtKurz")
|
|
171
|
+
message_long: str = Field(alias="nachrichtLang")
|
|
172
|
+
travel_direction_glyph: str = Field(alias="fahrtRichtungKennzeichen")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class Connection(BaseModel):
|
|
176
|
+
trip_id: str = Field(alias="tripId")
|
|
177
|
+
ctx_recon: str = Field(alias="ctxRecon")
|
|
178
|
+
segments: list[ConnectionSegment] = Field(alias="verbindungsAbschnitte")
|
|
179
|
+
changes: int = Field(alias="umstiegsAnzahl")
|
|
180
|
+
connection_time_in_seconds: int = Field(alias="verbindungsDauerInSeconds")
|
|
181
|
+
ez_connection_time_in_seconds: int | None = Field(None, alias="ezVerbindungsDauerInSeconds")
|
|
182
|
+
is_alternative_connection: bool = Field(alias="isAlternativeVerbindung")
|
|
183
|
+
utilizations: list[TrainUtilization] = Field(default_factory=list, alias="auslastungsmeldungen")
|
|
184
|
+
utilization_texts: list[TrainUtilizationText] = Field(default_factory=list, alias="auslastungstexte")
|
|
185
|
+
notes: list[ConnectionSegmentNote] = Field(alias="risNotizen")
|
|
186
|
+
messages: list[ConnectionSegmentMessage] = Field(alias="himMeldungen")
|
|
187
|
+
prioritized_messages: list[ConnectionSegmentPrioritizedMessage] = Field(alias="priorisierteMeldungen")
|
|
188
|
+
reservation_messages: list[Any] = Field(alias="reservierungsMeldungen")
|
|
189
|
+
is_bid_solicitation_requested: bool = Field(alias="isAngebotseinholungNachgelagert")
|
|
190
|
+
is_age_specification_required: bool = Field(alias="isAlterseingabeErforderlich")
|
|
191
|
+
service_days: list[ServiceDays] = Field(alias="serviceDays", default_factory=list)
|
|
192
|
+
event_summary: ResultSummary | None = Field(None, alias="ereignisZusammenfassung")
|
|
193
|
+
price: OfferPrice | None = Field(None, alias="angebotsPreis")
|
|
194
|
+
offer_price_class: str | None = Field(None, alias="angebotsPreisKlasse")
|
|
195
|
+
has_partial_price: bool = Field(alias="hasTeilpreis")
|
|
196
|
+
offers: list[Any] = Field(alias="reiseAngebote")
|
|
197
|
+
offer_informations: list[str] = Field(alias="angebotsInformationen", default_factory=list)
|
|
198
|
+
offer_informations_objects: list[OfferInformation] = Field(
|
|
199
|
+
alias="angebotsInformationenAsObject", default_factory=list
|
|
200
|
+
)
|
|
201
|
+
back_and_forth_combined_price: bool = Field(alias="hinRueckPauschalpreis")
|
|
202
|
+
is_reservation_outside_of_pre_booking_period: bool = Field(alias="isReservierungAusserhalbVorverkaufszeitraum")
|
|
203
|
+
complete_offer_list: list[Any] = Field(alias="gesamtAngebotsbeziehungList")
|
|
204
|
+
|
|
205
|
+
@property
|
|
206
|
+
def ez_connection_time(self) -> timedelta | None:
|
|
207
|
+
if self.ez_connection_time_in_seconds is not None:
|
|
208
|
+
return timedelta(seconds=self.ez_connection_time_in_seconds)
|
|
209
|
+
return None
|
|
210
|
+
|
|
211
|
+
@property
|
|
212
|
+
def ez_connection_time_string(self) -> str | None:
|
|
213
|
+
if self.ez_connection_time is not None:
|
|
214
|
+
return timedelta_to_hours_and_seconds_string(self.ez_connection_time)
|
|
215
|
+
return None
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def connection_time(self) -> timedelta:
|
|
219
|
+
return timedelta(seconds=self.connection_time_in_seconds)
|
|
220
|
+
|
|
221
|
+
@property
|
|
222
|
+
def connection_time_string(self) -> str:
|
|
223
|
+
return timedelta_to_hours_and_seconds_string(self.connection_time)
|
|
224
|
+
|
|
225
|
+
@property
|
|
226
|
+
def planned_departure_time(self) -> datetime | None:
|
|
227
|
+
return self.segments[0].departure_time
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def planned_arrival_time(self) -> datetime | None:
|
|
231
|
+
return self.segments[-1].arrival_time
|
|
232
|
+
|
|
233
|
+
@property
|
|
234
|
+
def actual_departure_time(self) -> datetime | None:
|
|
235
|
+
return self.segments[0].ez_departure_time
|
|
236
|
+
|
|
237
|
+
@property
|
|
238
|
+
def actual_arrival_time(self) -> datetime | None:
|
|
239
|
+
return self.segments[-1].ez_arrival_time
|
|
240
|
+
|
|
241
|
+
@property
|
|
242
|
+
def delay_departure(self) -> timedelta:
|
|
243
|
+
if self.planned_departure_time and self.actual_departure_time:
|
|
244
|
+
return self.actual_departure_time - self.planned_departure_time
|
|
245
|
+
return timedelta(0)
|
|
246
|
+
|
|
247
|
+
@property
|
|
248
|
+
def delay_arrival(self) -> timedelta:
|
|
249
|
+
if self.planned_arrival_time and self.actual_arrival_time:
|
|
250
|
+
return self.actual_arrival_time - self.planned_arrival_time
|
|
251
|
+
return timedelta(0)
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def cancelled(self) -> bool:
|
|
255
|
+
return any(note.key == CANCELLED_MESSAGE_KEY for note in self.notes)
|
|
256
|
+
|
|
257
|
+
@property
|
|
258
|
+
def direct(self) -> bool:
|
|
259
|
+
return self.changes == 0
|
|
260
|
+
|
|
261
|
+
@property
|
|
262
|
+
def on_time(self) -> bool:
|
|
263
|
+
return self.delay_arrival == timedelta(0)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
class ConnectionResponse(BaseModel):
|
|
267
|
+
connections: list[Connection] = Field(alias="verbindungen")
|
|
268
|
+
reference: Reference = Field(alias="verbindungReference")
|
|
269
|
+
|
|
270
|
+
@property
|
|
271
|
+
def has_more(self) -> bool:
|
|
272
|
+
return self.reference is not None and self.reference.later is not None
|
|
273
|
+
|
|
274
|
+
@property
|
|
275
|
+
def next_pointer(self) -> str | None:
|
|
276
|
+
if not self.has_more:
|
|
277
|
+
return None
|
|
278
|
+
return self.reference.later
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
class RequestType(Enum):
|
|
282
|
+
DEPARTURE = "ABFAHRT"
|
|
283
|
+
ARRIVAL = "ANKUNFT"
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class ProductType(Enum):
|
|
287
|
+
ICE = "ICE"
|
|
288
|
+
EC_IC = "EC_IC"
|
|
289
|
+
IR = "IR"
|
|
290
|
+
REGIONAL = "REGIONAL"
|
|
291
|
+
SBAHN = "SBAHN"
|
|
292
|
+
BUS = "BUS"
|
|
293
|
+
SHIP = "SCHIFF"
|
|
294
|
+
UBAHN = "UBAHN"
|
|
295
|
+
TRAM = "TRAM"
|
|
296
|
+
CALL_REQUIRED = "ANRUFPFLICHTIG"
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class TravellerType(Enum):
|
|
300
|
+
ADULT = "ERWACHSENER"
|
|
301
|
+
SENIOR = "SENIOR"
|
|
302
|
+
YOUNG_ADULT = "JUGENDLICHER"
|
|
303
|
+
FAMILY_CHILD = "FAMILIENKIND"
|
|
304
|
+
BABY = "KLEINKIND"
|
|
305
|
+
DISABLED = "BEHINDERT"
|
|
306
|
+
PET = "HAUSTIER"
|
|
307
|
+
BICYCLE = "FAHRRAD"
|
|
308
|
+
DOG = "HUND"
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
class ReductionType(Enum):
|
|
312
|
+
BAHNCARD100 = "BAHNCARD100"
|
|
313
|
+
BAHNCARD50 = "BAHNCARD50"
|
|
314
|
+
BAHNCARD25 = "BAHNCARD25"
|
|
315
|
+
BAHNCARDBUSINESS50 = "BAHNCARDBUSINESS50"
|
|
316
|
+
BAHNCARDBUSINESS25 = "BAHNCARDBUSINESS25"
|
|
317
|
+
CHGENERALABONNEMENT = "CH-GENERAL-ABONNEMENT"
|
|
318
|
+
KLIMATICKETOE = "KLIMATICKET_OE"
|
|
319
|
+
CHHALBTAGSABO = "CH-HALBTAXABO_OHNE_RAILPLUS"
|
|
320
|
+
VORTEILSCARD_OESTERREICH = "A-VORTEILSCARD"
|
|
321
|
+
NL40 = "NL-40_OHNE_RAILPLUS"
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
class Reduction(BaseModel):
|
|
325
|
+
type: ReductionType = Field(alias="art")
|
|
326
|
+
ticket_class: Literal["KLASSE_1", "KLASSE_2", "KLASSENLOS"] = Field(alias="klasse")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
BahnCard100Reduction1stClass = Reduction(type=ReductionType.BAHNCARD100, ticket_class="KLASSE_1")
|
|
330
|
+
BahnCard100Reduction2ndClass = Reduction(type=ReductionType.BAHNCARD100, ticket_class="KLASSE_2")
|
|
331
|
+
BahnCard50Reduction1stClass = Reduction(type=ReductionType.BAHNCARD50, ticket_class="KLASSE_1")
|
|
332
|
+
BahnCard50Reduction2ndClass = Reduction(type=ReductionType.BAHNCARD50, ticket_class="KLASSE_2")
|
|
333
|
+
BahnCard25Reduction1stClass = Reduction(type=ReductionType.BAHNCARD25, ticket_class="KLASSE_1")
|
|
334
|
+
BahnCard25Reduction2ndClass = Reduction(type=ReductionType.BAHNCARD25, ticket_class="KLASSE_2")
|
|
335
|
+
BahnCardBusiness50Reduction1stClass = Reduction(type=ReductionType.BAHNCARDBUSINESS50, ticket_class="KLASSE_1")
|
|
336
|
+
BahnCardBusiness50Reduction2ndClass = Reduction(type=ReductionType.BAHNCARDBUSINESS50, ticket_class="KLASSE_2")
|
|
337
|
+
BahnCardBusiness25Reduction1stClass = Reduction(type=ReductionType.BAHNCARDBUSINESS25, ticket_class="KLASSE_1")
|
|
338
|
+
BahnCardBusiness25Reduction2ndClass = Reduction(type=ReductionType.BAHNCARDBUSINESS25, ticket_class="KLASSE_2")
|
|
339
|
+
ChGeneralAbonnementReduction1stClass = Reduction(type=ReductionType.CHGENERALABONNEMENT, ticket_class="KLASSE_1")
|
|
340
|
+
ChGeneralAbonnementReduction2ndClass = Reduction(type=ReductionType.CHGENERALABONNEMENT, ticket_class="KLASSE_2")
|
|
341
|
+
KlimaticketOeReduction = Reduction(type=ReductionType.KLIMATICKETOE, ticket_class="KLASSE_2")
|
|
342
|
+
ChHalbtaxaboReduction = Reduction(type=ReductionType.CHHALBTAGSABO, ticket_class="KLASSENLOS")
|
|
343
|
+
VorteilsCardOesterreichReduction = Reduction(type=ReductionType.VORTEILSCARD_OESTERREICH, ticket_class="KLASSENLOS")
|
|
344
|
+
NL40Reduction = Reduction(type=ReductionType.NL40, ticket_class="KLASSENLOS")
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
class Traveller(BaseModel):
|
|
348
|
+
age: list[Any] = Field(alias="alter")
|
|
349
|
+
numbers: int = Field(alias="anzahl")
|
|
350
|
+
traveller_type: TravellerType = Field(alias="typ")
|
|
351
|
+
reductions: list[Reduction] = Field(alias="ermaessigungen")
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
class ConnectionRequest(BaseModel):
|
|
355
|
+
origin: str = Field(alias="abfahrtsHalt")
|
|
356
|
+
destination: str = Field(alias="ankunftsHalt")
|
|
357
|
+
time: datetime = Field(alias="anfrageZeitpunkt", default_factory=datetime.now)
|
|
358
|
+
search_type: RequestType = Field(RequestType.DEPARTURE, alias="ankunftSuche")
|
|
359
|
+
bike_carriage: bool = Field(False, alias="bikeCarriage")
|
|
360
|
+
germany_ticket_available: bool = Field(False, alias="deutschlandTicketVorhanden")
|
|
361
|
+
ticket_class: Literal["KLASSE_1", "KLASSE_2"] = Field("KLASSE_2", alias="klasse")
|
|
362
|
+
germany_ticket_allowed_connections: bool = Field(False, alias="nurDeutschlandTicketVerbindungen")
|
|
363
|
+
product_types: list[ProductType] = Field(alias="produktgattungen", default_factory=lambda: list(ProductType))
|
|
364
|
+
travellers: list[Traveller] = Field(
|
|
365
|
+
alias="reisende",
|
|
366
|
+
default_factory=lambda: [
|
|
367
|
+
Traveller(
|
|
368
|
+
age=[],
|
|
369
|
+
numbers=1,
|
|
370
|
+
traveller_type=TravellerType.ADULT,
|
|
371
|
+
reductions=[],
|
|
372
|
+
)
|
|
373
|
+
],
|
|
374
|
+
)
|
|
375
|
+
reservation_contingent_existing: bool = Field(False, alias="reservierungsKontingenteVorhanden")
|
|
376
|
+
fast_connections: bool = Field(True, alias="schnelleVerbindungen")
|
|
377
|
+
seating_space_only: bool = Field(False, alias="sitzplatzOnly")
|
|
378
|
+
paging_reference: str | None = Field(None, alias="pagingReference")
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
class Association(BaseModel):
|
|
382
|
+
code: str = Field(alias="code")
|
|
383
|
+
has_shop: bool = Field(alias="hatShop")
|
|
384
|
+
abbreviation: str = Field(alias="kuerzel")
|
|
385
|
+
description: str = Field(alias="description")
|
|
386
|
+
short_description: str = Field(alias="shortDescription")
|
|
387
|
+
logo: str = Field(alias="logo")
|
weiche/schiene.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from typing import TypedDict
|
|
3
|
+
|
|
4
|
+
from weiche.api.synchronous import SynchronousApi
|
|
5
|
+
from weiche.objects import Connection, Location
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SchieneStation(TypedDict):
|
|
9
|
+
extId: str
|
|
10
|
+
id: str
|
|
11
|
+
prodClass: str
|
|
12
|
+
state: str
|
|
13
|
+
type: str
|
|
14
|
+
typeStr: str
|
|
15
|
+
value: str
|
|
16
|
+
weight: str
|
|
17
|
+
xcoord: str
|
|
18
|
+
ycoord: str
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class SchieneConnectionDelay(TypedDict):
|
|
22
|
+
delay_arrival: int
|
|
23
|
+
delay_departure: int
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SchieneConnection(TypedDict):
|
|
27
|
+
arrival: str
|
|
28
|
+
canceled: bool
|
|
29
|
+
departure: str
|
|
30
|
+
delay: SchieneConnectionDelay | None
|
|
31
|
+
details: str
|
|
32
|
+
price: float | None
|
|
33
|
+
products: list[str]
|
|
34
|
+
time: str
|
|
35
|
+
transfers: int
|
|
36
|
+
ontime: bool
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def datetime_to_time_string(dt: datetime | None) -> str:
|
|
40
|
+
if dt is None:
|
|
41
|
+
return ""
|
|
42
|
+
return dt.strftime("%H:%M")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def connection_to_dict(connection: Connection) -> SchieneConnection:
|
|
46
|
+
if connection.price is None:
|
|
47
|
+
amount = None
|
|
48
|
+
else:
|
|
49
|
+
amount = connection.price.amount
|
|
50
|
+
|
|
51
|
+
payload = SchieneConnection(
|
|
52
|
+
arrival=datetime_to_time_string(connection.planned_arrival_time),
|
|
53
|
+
canceled=connection.cancelled,
|
|
54
|
+
departure=datetime_to_time_string(connection.planned_departure_time),
|
|
55
|
+
details="",
|
|
56
|
+
price=amount,
|
|
57
|
+
products=[
|
|
58
|
+
segment.means_of_transport.product_type
|
|
59
|
+
for segment in connection.segments
|
|
60
|
+
if segment.means_of_transport.product_type
|
|
61
|
+
],
|
|
62
|
+
time=connection.ez_connection_time_string or connection.connection_time_string,
|
|
63
|
+
transfers=connection.changes,
|
|
64
|
+
ontime=connection.on_time,
|
|
65
|
+
delay=None,
|
|
66
|
+
)
|
|
67
|
+
if not connection.on_time:
|
|
68
|
+
payload["delay"] = SchieneConnectionDelay(
|
|
69
|
+
delay_departure=int(connection.delay_departure.total_seconds() // 60),
|
|
70
|
+
delay_arrival=int(connection.delay_arrival.total_seconds() // 60),
|
|
71
|
+
)
|
|
72
|
+
return payload
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def schiene_to_dict(location: Location, index: int) -> SchieneStation:
|
|
76
|
+
return SchieneStation(
|
|
77
|
+
extId=location.ext_id,
|
|
78
|
+
id=location.id,
|
|
79
|
+
prodClass=",".join(product for product in location.products if product),
|
|
80
|
+
state="id",
|
|
81
|
+
type=location.type,
|
|
82
|
+
typeStr=location.type,
|
|
83
|
+
value=location.name,
|
|
84
|
+
weight=str(index),
|
|
85
|
+
xcoord=str(int(location.lon * 1_000_000)),
|
|
86
|
+
ycoord=str(int(location.lat * 1_000_000)),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Schiene:
|
|
91
|
+
def __init__(self):
|
|
92
|
+
self.api = SynchronousApi()
|
|
93
|
+
|
|
94
|
+
def stations(self, station: str, limit: int = 10) -> list[SchieneStation]:
|
|
95
|
+
"""Find stations for given queries.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
station (str): search query
|
|
99
|
+
limit (int): limit number of results
|
|
100
|
+
"""
|
|
101
|
+
stations = []
|
|
102
|
+
locations = self.api.search_locations(station, limit=limit)
|
|
103
|
+
for index, location in enumerate(locations):
|
|
104
|
+
stations.append(schiene_to_dict(location, index))
|
|
105
|
+
return stations
|
|
106
|
+
|
|
107
|
+
def connections(
|
|
108
|
+
self, origin: str, destination: str, dt: datetime = datetime.now(), only_direct: bool = False
|
|
109
|
+
) -> list[SchieneConnection]:
|
|
110
|
+
"""Find connections between two stations.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
origin (str): origin station
|
|
114
|
+
destination (str): destination station
|
|
115
|
+
dt (datetime): date and time for query
|
|
116
|
+
only_direct (bool): only direct connections
|
|
117
|
+
"""
|
|
118
|
+
origin_locations = self.api.search_locations(origin, limit=1)
|
|
119
|
+
if not origin_locations:
|
|
120
|
+
return []
|
|
121
|
+
origin_location = origin_locations[0]
|
|
122
|
+
destination_locations = self.api.search_locations(destination, limit=1)
|
|
123
|
+
if not destination_locations:
|
|
124
|
+
return []
|
|
125
|
+
destination_location = destination_locations[0]
|
|
126
|
+
connections = self.api.search_connections(
|
|
127
|
+
at=dt,
|
|
128
|
+
from_location=origin_location.id,
|
|
129
|
+
to_location=destination_location.id,
|
|
130
|
+
limit=10,
|
|
131
|
+
)
|
|
132
|
+
if only_direct:
|
|
133
|
+
connections = [c for c in connections if c.direct]
|
|
134
|
+
|
|
135
|
+
return [connection_to_dict(c) for c in connections]
|
weiche/tests/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""weiche."""
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from weiche import AsynchronousApi
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@pytest.mark.asyncio
|
|
9
|
+
async def test_connections_api() -> None:
|
|
10
|
+
api = AsynchronousApi()
|
|
11
|
+
munich_locations = await api.search_locations("München Hbf", limit=1)
|
|
12
|
+
assert len(munich_locations) == 1
|
|
13
|
+
munich = munich_locations[0]
|
|
14
|
+
|
|
15
|
+
berlin_locations = await api.search_locations("Berlin Hbf", limit=1)
|
|
16
|
+
assert len(berlin_locations) == 1
|
|
17
|
+
berlin = berlin_locations[0]
|
|
18
|
+
|
|
19
|
+
connections = await api.search_connections(
|
|
20
|
+
at=datetime.now(),
|
|
21
|
+
from_location=munich.id,
|
|
22
|
+
to_location=berlin.id,
|
|
23
|
+
limit=10,
|
|
24
|
+
)
|
|
25
|
+
assert len(connections) == 10
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from weiche import Schiene
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@pytest.mark.parametrize("only_direct", [True, False])
|
|
9
|
+
def test_connections_api(only_direct: bool) -> None:
|
|
10
|
+
api = Schiene()
|
|
11
|
+
response = api.connections("München Hbf", "Berlin Hbf", dt=datetime.now(), only_direct=True)
|
|
12
|
+
assert len(response) > 0
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_stations_api() -> None:
|
|
16
|
+
api = Schiene()
|
|
17
|
+
response = api.stations("München Hbf", limit=1)
|
|
18
|
+
assert len(response) == 1
|
|
19
|
+
assert response[0]["prodClass"] == "ICE,EC_IC,IR,REGIONAL,SBAHN,BUS,UBAHN,TRAM"
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from weiche import SynchronousApi
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_connections_api() -> None:
|
|
9
|
+
api = SynchronousApi()
|
|
10
|
+
munich_locations = api.search_locations("München Hbf", limit=1)
|
|
11
|
+
assert len(munich_locations) == 1
|
|
12
|
+
munich = munich_locations[0]
|
|
13
|
+
|
|
14
|
+
berlin_locations = api.search_locations("Berlin Hbf", limit=1)
|
|
15
|
+
assert len(berlin_locations) == 1
|
|
16
|
+
berlin = berlin_locations[0]
|
|
17
|
+
|
|
18
|
+
connections = api.search_connections(
|
|
19
|
+
at=datetime.now(),
|
|
20
|
+
from_location=munich.id,
|
|
21
|
+
to_location=berlin.id,
|
|
22
|
+
limit=10,
|
|
23
|
+
)
|
|
24
|
+
assert len(connections) == 10
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@pytest.mark.parametrize("target", ["Amsterdam", "Wien Hbf", "Paris", "London"])
|
|
28
|
+
def test_connections_api_international(target: str) -> None:
|
|
29
|
+
api = SynchronousApi()
|
|
30
|
+
munich_locations = api.search_locations("München Hbf", limit=1)
|
|
31
|
+
assert len(munich_locations) == 1
|
|
32
|
+
munich = munich_locations[0]
|
|
33
|
+
|
|
34
|
+
target_locations = api.search_locations(target, limit=1)
|
|
35
|
+
assert len(target_locations) == 1
|
|
36
|
+
target_obj = target_locations[0]
|
|
37
|
+
|
|
38
|
+
connections = api.search_connections(
|
|
39
|
+
at=datetime(2025, 5, 10, 18, 0, 0),
|
|
40
|
+
from_location=munich.id,
|
|
41
|
+
to_location=target_obj.id,
|
|
42
|
+
)
|
|
43
|
+
assert len(connections) > 0
|
weiche/version.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# file generated by setuptools-scm
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
|
|
4
|
+
__all__ = ["__version__", "__version_tuple__", "version", "version_tuple"]
|
|
5
|
+
|
|
6
|
+
TYPE_CHECKING = False
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from typing import Tuple
|
|
9
|
+
from typing import Union
|
|
10
|
+
|
|
11
|
+
VERSION_TUPLE = Tuple[Union[int, str], ...]
|
|
12
|
+
else:
|
|
13
|
+
VERSION_TUPLE = object
|
|
14
|
+
|
|
15
|
+
version: str
|
|
16
|
+
__version__: str
|
|
17
|
+
__version_tuple__: VERSION_TUPLE
|
|
18
|
+
version_tuple: VERSION_TUPLE
|
|
19
|
+
|
|
20
|
+
__version__ = version = '0.9.2.dev0'
|
|
21
|
+
__version_tuple__ = version_tuple = (0, 9, 2, 'dev0')
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: weiche
|
|
3
|
+
Version: 0.9.1
|
|
4
|
+
Summary: A wrapper around the DB Website API for querying train connections.
|
|
5
|
+
Author-email: Christoph Brand <christoph+pypi@brand.rest>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2025 Christoph Brand
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/cbrand/weiche
|
|
29
|
+
Classifier: Development Status :: 3 - Alpha
|
|
30
|
+
Classifier: Intended Audience :: Developers
|
|
31
|
+
Classifier: License :: OSI Approved :: MIT No Attribution License (MIT-0)
|
|
32
|
+
Classifier: Programming Language :: Python
|
|
33
|
+
Classifier: Programming Language :: Python :: 3
|
|
34
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
35
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
36
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
37
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
38
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
39
|
+
Requires-Python: >=3.10
|
|
40
|
+
Description-Content-Type: text/markdown
|
|
41
|
+
License-File: LICENSE
|
|
42
|
+
Requires-Dist: pydantic<3,>=2
|
|
43
|
+
Provides-Extra: test
|
|
44
|
+
Requires-Dist: pytest; extra == "test"
|
|
45
|
+
Requires-Dist: pytest-asyncio; extra == "test"
|
|
46
|
+
Requires-Dist: tox; extra == "test"
|
|
47
|
+
Requires-Dist: requests; extra == "test"
|
|
48
|
+
Requires-Dist: aiohttp; extra == "test"
|
|
49
|
+
Provides-Extra: sync
|
|
50
|
+
Requires-Dist: requests; extra == "sync"
|
|
51
|
+
Provides-Extra: async
|
|
52
|
+
Requires-Dist: aiohttp; extra == "async"
|
|
53
|
+
Provides-Extra: schiene
|
|
54
|
+
Requires-Dist: requests; extra == "schiene"
|
|
55
|
+
Dynamic: license-file
|
|
56
|
+
|
|
57
|
+
# 🚆 weiche
|
|
58
|
+
|
|
59
|
+
This is an unofficial library wrapper around the API of the
|
|
60
|
+
Deutsche Bahn (DB) website for identifying connections.
|
|
61
|
+
It returns **realtime**, **live** data.
|
|
62
|
+
If you do not need this in your project I strongly recommend
|
|
63
|
+
not to use this API as it might break any moment if DB changes
|
|
64
|
+
the API for getting station and train connections.
|
|
65
|
+
|
|
66
|
+
It has a API compatibility layer to the
|
|
67
|
+
[`schiene`](https://pypi.org/project/schiene/) package for
|
|
68
|
+
easy drop-in replacement as
|
|
69
|
+
[`schiene`](https://pypi.org/project/schiene/) no longer
|
|
70
|
+
works.
|
|
71
|
+
|
|
72
|
+
## Requirements
|
|
73
|
+
|
|
74
|
+
- Python 3.10 and above
|
|
75
|
+
- requests package for the synchronous API and Schiene wrapper
|
|
76
|
+
- aiohttp for the asynchronous API
|
|
77
|
+
|
|
78
|
+
## Features
|
|
79
|
+
|
|
80
|
+
- Get connections between two stations
|
|
81
|
+
- Search stations by name
|
|
82
|
+
- Get station information
|
|
83
|
+
|
|
84
|
+
## Setup
|
|
85
|
+
|
|
86
|
+
$ python -m venv /path/to/venv
|
|
87
|
+
$ /path/to/venv/bin/python -m pip install weiche[sync,async,schiene]
|
|
88
|
+
|
|
89
|
+
## Usage
|
|
90
|
+
|
|
91
|
+
### Use the synchronous API
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from datetime import datetime
|
|
95
|
+
from weiche import SynchronousApi
|
|
96
|
+
|
|
97
|
+
api = SynchronousApi()
|
|
98
|
+
|
|
99
|
+
amsterdam_query = api.search_locations('Amsterdam', limit=1)
|
|
100
|
+
amsterdam = amsterdam_query[0]
|
|
101
|
+
munich_query = api.search_locations('München Hbf', limit=1)
|
|
102
|
+
munich = munich_query[0]
|
|
103
|
+
|
|
104
|
+
api.search_connections(
|
|
105
|
+
at=datetime(2025,5,10,18,0,0),
|
|
106
|
+
from_location=munich.id,
|
|
107
|
+
to_location=amsterdam.id,
|
|
108
|
+
limit=10,
|
|
109
|
+
)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
<details>
|
|
113
|
+
<summary>Response from Synchronous API</summary>
|
|
114
|
+
|
|
115
|
+
The return format is an object which can also be found in the [objects.py](./src/weiche/objects.py) file.
|
|
116
|
+
|
|
117
|
+
Look for the [`Connection`](./src/weiche/objects.py#L175) class and see the API definition there.
|
|
118
|
+
|
|
119
|
+
</details>
|
|
120
|
+
|
|
121
|
+
### Use the asynchronous API
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
import asyncio
|
|
125
|
+
from datetime import datetime
|
|
126
|
+
from weiche import AsynchronousApi
|
|
127
|
+
|
|
128
|
+
async def search():
|
|
129
|
+
api = AsynchronousApi()
|
|
130
|
+
|
|
131
|
+
amsterdam_query = await api.search_locations('Amsterdam', limit=1)
|
|
132
|
+
amsterdam = amsterdam_query[0]
|
|
133
|
+
munich_query = await api.search_locations('München Hbf', limit=1)
|
|
134
|
+
munich = munich_query[0]
|
|
135
|
+
|
|
136
|
+
return await api.search_connections(
|
|
137
|
+
at=datetime(2025,5,10,18,0,0),
|
|
138
|
+
from_location=munich.id,
|
|
139
|
+
to_location=amsterdam.id,
|
|
140
|
+
limit=10,
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
asyncio.get_event_loop().run_until_complete(search())
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
<details>
|
|
147
|
+
<summary>Response from Asynchronous API</summary>
|
|
148
|
+
|
|
149
|
+
The return format is an object which can also be found in the [objects.py](./src/weiche/objects.py) file.
|
|
150
|
+
|
|
151
|
+
Look for the [`Connection`](./src/weiche/objects.py#L175) class and see the API definition there.
|
|
152
|
+
|
|
153
|
+
</details>
|
|
154
|
+
|
|
155
|
+
### Use the `schiene` compatibility layer
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
from weiche import Schiene
|
|
159
|
+
|
|
160
|
+
Schiene().connections('Mannheim HbF', 'Stuttgart HbF')
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
<details>
|
|
164
|
+
<summary>Response from Schiene Layer</summary>
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
[{'arrival': '15:47',
|
|
168
|
+
'canceled': False,
|
|
169
|
+
'departure': '14:30',
|
|
170
|
+
'details': '',
|
|
171
|
+
'price': 55.0,
|
|
172
|
+
'products': ['ICE'],
|
|
173
|
+
'time': '01:16',
|
|
174
|
+
'transfers': 0,
|
|
175
|
+
'ontime': True,
|
|
176
|
+
'delay': None},
|
|
177
|
+
{'arrival': '16:21',
|
|
178
|
+
'canceled': False,
|
|
179
|
+
'departure': '14:38',
|
|
180
|
+
'details': '',
|
|
181
|
+
'price': 50.99,
|
|
182
|
+
'products': ['SBAHN', 'ICE'],
|
|
183
|
+
'time': '01:42',
|
|
184
|
+
'transfers': 1,
|
|
185
|
+
'ontime': True,
|
|
186
|
+
'delay': None},
|
|
187
|
+
{'arrival': '16:25',
|
|
188
|
+
'canceled': False,
|
|
189
|
+
'departure': '14:46',
|
|
190
|
+
'details': '',
|
|
191
|
+
'price': 50.99,
|
|
192
|
+
'products': ['ICE', 'REGIONAL'],
|
|
193
|
+
'time': '01:23',
|
|
194
|
+
'transfers': 1,
|
|
195
|
+
'ontime': True,
|
|
196
|
+
'delay': None},
|
|
197
|
+
{'arrival': '16:45',
|
|
198
|
+
'canceled': False,
|
|
199
|
+
'departure': '15:31',
|
|
200
|
+
'details': '',
|
|
201
|
+
'price': 55.0,
|
|
202
|
+
'products': ['ICE'],
|
|
203
|
+
'time': '01:14',
|
|
204
|
+
'transfers': 0,
|
|
205
|
+
'ontime': True,
|
|
206
|
+
'delay': None},
|
|
207
|
+
{'arrival': '17:27',
|
|
208
|
+
'canceled': False,
|
|
209
|
+
'departure': '15:34',
|
|
210
|
+
'details': '',
|
|
211
|
+
'price': 55.0,
|
|
212
|
+
'products': ['ICE', 'REGIONAL'],
|
|
213
|
+
'time': '01:53',
|
|
214
|
+
'transfers': 1,
|
|
215
|
+
'ontime': True,
|
|
216
|
+
'delay': None},
|
|
217
|
+
{'arrival': '17:15',
|
|
218
|
+
'canceled': False,
|
|
219
|
+
'departure': '15:35',
|
|
220
|
+
'details': '',
|
|
221
|
+
'price': 21.8,
|
|
222
|
+
'products': ['REGIONAL', 'REGIONAL'],
|
|
223
|
+
'time': '01:40',
|
|
224
|
+
'transfers': 1,
|
|
225
|
+
'ontime': True,
|
|
226
|
+
'delay': None},
|
|
227
|
+
{'arrival': '17:44',
|
|
228
|
+
'canceled': False,
|
|
229
|
+
'departure': '15:35',
|
|
230
|
+
'details': '',
|
|
231
|
+
'price': 21.8,
|
|
232
|
+
'products': ['REGIONAL', 'REGIONAL'],
|
|
233
|
+
'time': '02:09',
|
|
234
|
+
'transfers': 1,
|
|
235
|
+
'ontime': True,
|
|
236
|
+
'delay': None},
|
|
237
|
+
{'arrival': '17:33',
|
|
238
|
+
'canceled': False,
|
|
239
|
+
'departure': '15:36',
|
|
240
|
+
'details': '',
|
|
241
|
+
'price': 24.99,
|
|
242
|
+
'products': ['SBAHN', 'ICE'],
|
|
243
|
+
'time': '02:06',
|
|
244
|
+
'transfers': 1,
|
|
245
|
+
'ontime': False,
|
|
246
|
+
'delay': {'delay_departure': 0, 'delay_arrival': 9}},
|
|
247
|
+
{'arrival': '18:20',
|
|
248
|
+
'canceled': False,
|
|
249
|
+
'departure': '16:38',
|
|
250
|
+
'details': '',
|
|
251
|
+
'price': 47.99,
|
|
252
|
+
'products': ['SBAHN', 'ICE'],
|
|
253
|
+
'time': '01:42',
|
|
254
|
+
'transfers': 1,
|
|
255
|
+
'ontime': True,
|
|
256
|
+
'delay': None},
|
|
257
|
+
{'arrival': '18:24',
|
|
258
|
+
'canceled': False,
|
|
259
|
+
'departure': '16:46',
|
|
260
|
+
'details': '',
|
|
261
|
+
'price': 50.99,
|
|
262
|
+
'products': ['ICE', 'REGIONAL'],
|
|
263
|
+
'time': '01:38',
|
|
264
|
+
'transfers': 1,
|
|
265
|
+
'ontime': True,
|
|
266
|
+
'delay': None}]
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
</details>
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
weiche/__init__.py,sha256=fWjA1zup1Cgndr03OFtSzf1YCBqrIlJRHoQmlgwCm5E,1061
|
|
2
|
+
weiche/const.py,sha256=4yrFXSfvvyjulaU8E3ApF95WvEBmftoislBQeZmBqFg,50
|
|
3
|
+
weiche/formatter.py,sha256=FoCayD6FgyIdqj55Hd7xelUiRuOKqO5R4vEW5dK6yt4,330
|
|
4
|
+
weiche/objects.py,sha256=KEPyp0bNxabNophXjXNSm3mDmsv3RBI9kqcdh33a1U8,15616
|
|
5
|
+
weiche/schiene.py,sha256=dBYkjZxVDZRqKNjeDiPi7jmAH97mh-8D037D8uhG9Dw,4075
|
|
6
|
+
weiche/version.py,sha256=UgXY_8I5Jjlyq5dLBnJ3okunWNxiCsAYziPsGFUHwQg,524
|
|
7
|
+
weiche/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
weiche/api/asynchronous.py,sha256=OY9mqC9CwhJob1oU5I816vpdH5jtoGk17kkhq8cmHCM,2658
|
|
9
|
+
weiche/api/base.py,sha256=XIrgEGpU67XaK0mcc0tPjyS3kleJW3bfGuk92qSh5C4,1554
|
|
10
|
+
weiche/api/parser.py,sha256=ncH69UFbrx7c06vkQFA19qvQMwy1DxWJfIv4EZ2I1E0,567
|
|
11
|
+
weiche/api/synchronous.py,sha256=v0WtwpLYoO_NZvAkJQIpWMTrZKJSsW16jtiUX6KlzI4,2548
|
|
12
|
+
weiche/tests/__init__.py,sha256=5UGrL_1j55tybMTGvcICYpuQ4KgbMT2zNZ_RfPjiFUs,14
|
|
13
|
+
weiche/tests/test_asynchronous.py,sha256=wsa0mkg-207a-2hK3w4agFhGrBNmbvVtd5BY_ebz11w,663
|
|
14
|
+
weiche/tests/test_schiene.py,sha256=Y8JHxAmWLNKstE3S4M4QMQLNfdnP9MioYTE7sfvss0w,552
|
|
15
|
+
weiche/tests/test_synchronous.py,sha256=bl_n29TuZ978lCq-WP6lr-a-PYL6wdd8zo-oo-Drmrs,1257
|
|
16
|
+
weiche-0.9.1.dist-info/licenses/LICENSE,sha256=JjZTWDUeGYQsqZg0q_a9s8bTEHXGWlZoxc0sFSmdOO8,1072
|
|
17
|
+
weiche-0.9.1.dist-info/METADATA,sha256=2WIbVtda3XSF6kInChcdl-0AaYC2tQ_zH5DcVmsh4Ys,7428
|
|
18
|
+
weiche-0.9.1.dist-info/WHEEL,sha256=DnLRTWE75wApRYVsjgc6wsVswC54sMSJhAEd4xhDpBk,91
|
|
19
|
+
weiche-0.9.1.dist-info/top_level.txt,sha256=34IT9Bl4oFq_AE1a8x3xtNzGG2dc-oHHaWtJJzNojFE,7
|
|
20
|
+
weiche-0.9.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Christoph Brand
|
|
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 @@
|
|
|
1
|
+
weiche
|