コード例 #1
0
def test_vsn_journey_request():
    client = HafasClient(VSNProfile())
    journey = client.journey(
        journey=
        "¶HKI¶T$A=1@O=Lenglern Bahnhof@L=9909403@a=128@$A=1@O=Göttingen Bahnhof/ZOB@L=1101000@a=128@$202106051527$202106051550$Bus 220 $$1$$$$",
    )
    assert isinstance(journey, Journey)
コード例 #2
0
def test_db_journey_request():
    client = HafasClient(DBProfile())
    journey = client.journey(
        journey=
        "¶HKI¶T$A=1@O=Siegburg/Bonn@L=8005556@a=128@$A=1@O=Hennef(Sieg)@L=8002753@a=128@$202106051440$202106051445$S     12$$1$$$",
    )
    assert isinstance(journey, Journey)
コード例 #3
0
def test_db_journey_request():
    client = HafasClient(DBProfile())
    journey = client.journey(
        journey=
        "¶HKI¶T$A=1@O=Siegburg/Bonn@L=8005556@a=128@$A=1@O=Troisdorf@L=8000135@a=128@$202008081507$202008081512$S     19$$1$$$c",
    )
    assert isinstance(journey, Journey)
コード例 #4
0
def dbapis_importstations_parse_station_row(row, agency_pk, source_pk,
                                            kind_pk):
    hafas_client = HafasClient(DBProfile())

    agency = Agency.objects.get(pk=agency_pk)
    source = Source.objects.get(pk=source_pk)
    kind = StopIDKind.objects.get(pk=kind_pk)
    if row['EVA_NR'] == '':
        return
    stop = Stop.objects.filter(
        stopid__name=row['EVA_NR'],
        stopid__kind__in=agency.used_id_kind.all()).first()
    if stop is None:
        stop = Stop()
        stop.save()
    StopName.objects.get_or_create(name=row['NAME'], stop=stop, source=source)
    StopID.objects.get_or_create(stop=stop,
                                 name=row['EVA_NR'],
                                 source=source,
                                 kind=kind)
    try:
        StopLocation.objects.get(stop=stop, source=source)
    except ObjectDoesNotExist:
        try:
            hafasLocation = hafas_client.locations(row['EVA_NR'])[0]
            StopLocation.objects.create(stop=stop,
                                        latitude=hafasLocation.latitude,
                                        longitude=hafasLocation.longitude,
                                        source=source)
        except IndexError:
            return
コード例 #5
0
ファイル: journey_test.py プロジェクト: p0l0/pyhafas
def test_vsn_journey_request():
    client = HafasClient(VSNProfile())
    journey = client.journey(
        journey=
        "¶HKI¶T$A=1@O=Göttingen@L=8000128@a=128@$A=1@O=Lenglern@L=8003644@a=128@$202008090710$202008090719$    RB85$$1$$$",
    )
    assert isinstance(journey, Journey)
    def handle(self, *args, **options):
        client = HafasClient(DBProfile())

        for start in STOPS:
            for end in STOPS:
                if start == end:
                    continue
                journeys = client.journeys(start,
                                           end,
                                           date=datetime.datetime.now())

                stops = [
                    Stop.objects.get(stopid__external_id=start),
                    Stop.objects.get(stopid__external_id=end)
                ]
                cons = Connection.objects.filter(stop=stops[0]).filter(
                    stop=stops[1])

                if len(cons):
                    con = cons[0]
                else:
                    con = Connection()
                    con.save()
                    con.stop.add(*stops)

                con.duration = datetime.timedelta(seconds=statistics.mean(
                    [j.duration.total_seconds() for j in journeys]))
                con.save()
コード例 #7
0
ファイル: journeys_test.py プロジェクト: p0l0/pyhafas
def test_vsn_journeys_request():
    client = HafasClient(VSNProfile())
    journeys = client.journeys(destination="009033817",
                               origin="009054997",
                               date=datetime.datetime.now(),
                               min_change_time=0,
                               max_changes=-1)
    assert journeys
コード例 #8
0
def test_db_journeys_request():
    client = HafasClient(DBProfile())
    journeys = client.journeys(destination="8000135",
                               origin="8005556",
                               date=datetime.datetime.now(),
                               min_change_time=0,
                               max_changes=-1)
    assert journeys
コード例 #9
0
 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)
コード例 #10
0
ファイル: example.py プロジェクト: p0l0/pyhafas
import datetime

from pyhafas import HafasClient
from pyhafas.profile import DBProfile, VSNProfile

client = HafasClient(DBProfile(), debug=True)

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)
コード例 #11
0
ファイル: arrivals_test.py プロジェクト: p0l0/pyhafas
def test_vsn_arrivals_request():
    client = HafasClient(VSNProfile())
    arrivals = client.arrivals(station="009033817",
                               date=datetime.datetime.now(),
                               max_trips=5)
    assert arrivals
コード例 #12
0
ファイル: departures_test.py プロジェクト: p0l0/pyhafas
def test_vsn_departures_request():
    client = HafasClient(VSNProfile())
    departures = client.departures(station="009033817",
                                   date=datetime.datetime.now(),
                                   max_trips=5)
    assert departures
コード例 #13
0
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()
コード例 #14
0
ファイル: arrivals_test.py プロジェクト: p0l0/pyhafas
def test_db_arrivals_request():
    client = HafasClient(DBProfile())
    arrivals = client.arrivals(station="8011160",
                               date=datetime.datetime.now(),
                               max_trips=2)
    assert len(arrivals) <= 2
コード例 #15
0
ファイル: locations_test.py プロジェクト: p0l0/pyhafas
def test_vsn_locations_request():
    client = HafasClient(VSNProfile())
    locations = client.locations(term="Göttingen Bahnhof/ZOB")
    assert len(locations) >= 1
コード例 #16
0
import os
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import datetime
from helpers import StationPhillip

from pyhafas import HafasClient
from pyhafas.profile import DBProfile

stations = StationPhillip()
hafas = HafasClient(DBProfile())

# location = hafas.locations()

journeys = hafas.journeys(
    origin=stations.get_eva(name='Tübingen Hbf'),
    destination=stations.get_eva(name='Köln Hbf'),
    date=datetime.datetime.now(),
)

print(journeys)
コード例 #17
0
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()
コード例 #18
0
def test_db_departures_request():
    client = HafasClient(DBProfile())
    departures = client.departures(station="8011160",
                                   date=datetime.datetime.now(),
                                   max_trips=2)
    assert len(departures) <= 2
コード例 #19
0
 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")
コード例 #20
0
ファイル: locations_test.py プロジェクト: p0l0/pyhafas
def test_db_locations_request():
    client = HafasClient(DBProfile())
    locations = client.locations(term="Köln Messe/Deutz")
    assert len(locations) >= 1
コード例 #21
0
import datetime

from pyhafas import HafasClient
from pyhafas.profile import RKRPProfile

client = HafasClient(RKRPProfile(), debug=True)

id_nordhavn = '8600653'
id_kongebakken9 = 'A=2@O=Kongebakken 9, 2765 Smørum, Egedal Kommune@X=12294403@Y=55749256@U=103@L=902400113@B=1@p=1618386996@'

#print(client.departures(
#    station=id_nordhavn,
#    date=datetime.datetime.now(),
#    max_trips=5
#))

#print(client.arrivals(
#    station=id_nordhavn,
#    date=datetime.datetime.now(),
#    max_trips=5
#))

# Test searching for an address
locs = client.locations("Kongebakken 9, 2765 Smørum", rtype='ALL')
assert (locs[0].lid == id_kongebakken9)

possibilities = client.journeys(origin=id_nordhavn,
                                destination=id_kongebakken9,
                                date=datetime.datetime.now(),
                                min_change_time=0,
                                max_changes=-1)