class HafasImport: def __init__(self): self.hafasclient = HafasClient(DBProfile()) self.db, _ = Agency.objects.get_or_create(name="db") self.dbapis, _ = Source.objects.get_or_create(name="dbapis") self.idkind, _ = StopIDKind.objects.get_or_create(name='eva') self.timezone = pytz.timezone("Europe/Berlin") def import_timetable(self, station, duration=90): try: stopid, _ = StopID.objects.get_or_create(stop=station, kind=self.idkind) except StopID.MultipleObjectsReturned: stopid = StopID.objects.filter(stop=station, kind=self.idkind).first() departure_legs = self.hafasclient.departures( station=stopid.name, date=datetime.datetime.now(), duration=duration, products={ 'long_distance_express': True, 'long_distance': True, 'regional_express': False, 'regional': False, 'suburban': False, 'bus': False, 'ferry': False, 'subway': False, 'tram': False, 'taxi': False }) for leg in departure_legs: if not Journey.objects.filter(journey_id=leg.id).exists(): Journey.objects.create(journey_id=leg.id, source=self.dbapis, agency=self.db, date=leg.dateTime.date(), name=leg.name) def import_journey(self, journey): try: trip = self.hafasclient.trip(journey.journey_id) except BaseException: # TODO: Implement correct Exception when pyhafas has them return for stopover in trip.stopovers: eva_id = stopover.stop.id[-8:] dbStopID = StopID.objects.filter(name=eva_id, source=self.dbapis).first() if dbStopID is None: print("The Stop {} with ID {} could not be found!".format( stopover.stop.name, eva_id)) continue dbStop = dbStopID.stop if JourneyStop.objects.filter(stop=dbStop, journey=journey).count() == 0: JourneyStop.objects.create( stop=dbStop, journey=journey, planned_departure_time=stopover.departure, actual_departure_delay=stopover.departureDelay, planned_arrival_time=stopover.arrival, actual_arrival_delay=stopover.arrivalDelay) else: journeyStop = JourneyStop.objects.get(stop=dbStop, journey=journey) if stopover.departureDelay is not None: journeyStop.actual_departure_delay = stopover.departureDelay if stopover.arrivalDelay is not None: journeyStop.actual_arrival_delay = stopover.arrivalDelay journeyStop.save()
print( client.departures(station='8000128', date=datetime.datetime.now(), max_trips=5)) print( client.arrivals(station='8005556', date=datetime.datetime.now(), max_trips=5)) print( client.journey( '¶HKI¶T$A=1@O=Berlin Jungfernheide@L=8011167@a=128@$A=1@O=Berlin Hbf (tief)@L=8098160@a=128@$202002101544$202002101549$RB 18521$$1$§T$A=1@O=Berlin Hbf (tief)@L=8098160@a=128@$A=1@O=München Hbf@L=8000261@a=128@$202002101605$202002102002$ICE 1007$$1$' )) print( client.journeys(destination="8000207", origin="8005556", date=datetime.datetime.now(), min_change_time=0, max_changes=-1)) print(client.locations("Köln Hbf")) print(client.trip("1|1372374|3|80|9062020")) print('=' * 20) vsn = HafasClient(VSNProfile()) print( vsn.departures(station='9034033', date=datetime.datetime.now(), max_journeys=5))
class HafasImport: def __init__(self): self.hafasclient = HafasClient(DBProfile()) self.provider = Provider.objects.get(internal_name="db") self.source, _ = Source.objects.get_or_create( internal_name="db_hafas", friendly_name="Deutsche Bahn HAFAS", provider=self.provider) self.idkind, _ = StopIDKind.objects.get_or_create( name='eva', provider=self.provider) def import_timetable(self, station, duration=90): stopid = StopID.objects.get(stop=station, kind=self.idkind) departure_legs = self.hafasclient.departures( station=stopid.external_id, date=datetime.datetime.now(), duration=duration, products={ 'long_distance_express': True, 'long_distance': True, 'regional_express': False, 'regional': False, 'suburban': False, 'bus': False, 'ferry': False, 'subway': False, 'tram': False, 'taxi': False }) for leg in departure_legs: if "Flug" in leg.name or "Os " in leg.name or "BUS" in leg.name or "R " in leg.name or "RB " in leg.name \ or "RE " in leg.name or "Sp " in leg.name or "STR " in leg.name or "BRB" in leg.name \ or "ARV" in leg.name or "S " in leg.name or "M " in leg.name: continue current_db_journeys = Journey.objects.filter( name=leg.name, date=leg.dateTime.date(), source=self.source) if current_db_journeys.count() == 0: Journey.objects.create(name=leg.name, date=leg.dateTime.date(), source=self.source, cancelled=leg.cancelled) else: journey = current_db_journeys.first() if journey.cancelled != leg.cancelled: journey.cancelled = leg.cancelled journey.save() def get_trip_id(self, journey: Journey): lid_request = requests.get( url="https://reiseauskunft.bahn.de/bin/trainsearch.exe/dn", params={ "L": "vs_json", "stationFilter": 80, "productClassFilter": 3, "date": journey.date.strftime("%d.%m.%Y"), "trainname": journey.name }) try: parsed_response = json.loads(lid_request.text[11:-1]) except JSONDecodeError: return None trains = parsed_response['suggestions'] if len(trains) == 0: return None first_train = trains[0] first_train_date = datetime.datetime.strptime( first_train['depDate'], '%d.%m.%Y').strftime('%d%m%Y') trip_id = f"1|{first_train['id']}|{first_train['cycle']}|{first_train['pool']}|{first_train_date}" return trip_id def import_journey(self, journey: Journey): trip_id = self.get_trip_id(journey) if trip_id is None: return try: trip = self.hafasclient.trip(trip_id) except GeneralHafasError as e: return for stopover in trip.stopovers: eva_id = stopover.stop.id[-8:] db_stop_id = StopID.objects.filter( external_id=eva_id, kind__name='eva', kind__provider=self.provider).first() if db_stop_id is None: print("The Stop {} with ID {} could not be found!".format( stopover.stop.name, eva_id)) continue db_stop = db_stop_id.stop current_db_journeystops = JourneyStop.objects.filter( stop=db_stop, journey=journey) if current_db_journeystops.count() == 0: JourneyStop.objects.create( stop=db_stop, journey=journey, planned_departure_time=stopover.departure, actual_departure_delay=stopover.departureDelay, planned_arrival_time=stopover.arrival, actual_arrival_delay=stopover.arrivalDelay, cancelled=stopover.cancelled) else: journey_stop = current_db_journeystops.first() if journey_stop.cancelled != stopover.cancelled: journey_stop.cancelled = stopover.cancelled if stopover.departureDelay is not None: journey_stop.actual_departure_delay = stopover.departureDelay if stopover.arrivalDelay is not None: journey_stop.actual_arrival_delay = stopover.arrivalDelay journey_stop.save()