class StopPointFetcher(object):  #TODO: Change name to reflect expanded scope
    """
    This class interacts with the Stops and Lines directory API https://www.trafiklab.se/api/sl-hallplatser-och-linjer-2
    """
    def __init__(self,
                 schema='json',
                 granularity='StopPoint'
                 ):  #TODO: Use json parameter in endpoint string formatter
        self.log = GLogger(name=__name__).get_logger()
        self.granularity = granularity
        self.API_KEY = trafiklab_key.key_stops_and_lines
        self.endpoint = (
            'http://api.sl.se/api2/LineData.{1}?model={2}&key={0}'.format(
                self.API_KEY, schema, granularity))

    def get_stop_points(self):
        result = requests.get(self.endpoint).json()
        self.log.info("Queried for {}".format(self.granularity))
        return result

    def download_stop_points(self):
        datetime_string = datetime.now().strftime('%Y%m%d-%H%M')
        filename = 'sl_{1}_{0}.json'.format(datetime_string, self.granularity)
        with open(filename, 'w') as f:
            f.write(json.dumps(self.get_stop_points()))
            self.log.info("{1} data written to {0}".format(
                filename, self.granularity))
        return 200
Beispiel #2
0
class DBHelper(object):
    def get_default_site(self, user_id):
        if user_id == 'amzn1.ask.account.AHQSD27I4E4GWTS7HVGEYTWOYS22TYUWHBU3OQN5QEJFLIRFX3YVZ6VL5XE5WWXKHHI7UA3ZS4WSGTQAZSO67643SGOCSEBOQZ35UCNDVPEVJKNKOEBERMJKUBUOHLCEII2XNI6DHHJ25TQZDSEDXHVGKGTMCFPOBNKM6ABUH3SNCPXFTEKAHNTN5FI5R5OWKEYOMHGLC22W3BQ':
            return 'sickla kaj'

    def __init__(self):
        self.log = GLogger(name=__name__).get_logger()
        self.log.info("Log initiated (DBHelper")
class Trafiklab(object):
    SITE_ID_SICKLAKAJ = "1550"
    BASE_URL = "http://api.sl.se/api2/realtimedeparturesV4.{schema}?key={key}&siteid={siteid}&timewindow={timewindow}"

    def get_full_response(self, url):
        # Returns a dict from the JSON provided by the Trafiklab API, given a compliant REST call
        import requests
        response = requests.get(url)
        return response.json()

    def get_trams(self):
        # Returns a namedtuple of tram destinations and departure times (values, as displayed on boards)
        response = requests.get(self.endpoint).json()
        self.log.info(response)
        trams = []
        Departure = namedtuple('Departure',
                               ['destination', 'display_time', 'line_number'])
        for dept in response["ResponseData"]["Trams"]:
            self.log.info("Got {}".format(dept))
            trams.append(
                Departure(dept["Destination"], dept["DisplayTime"],
                          dept['LineNumber']))
        return trams

    def get_buses(self, **kwargs):
        # Returns a namedtuple of bus destinations and departure times (values, as displayed on boards)
        response = requests.get(self.endpoint).json()
        # self.log.info(response)
        buses = []
        Departure = namedtuple('Departure',
                               ['destination', 'display_time', 'line_number'])
        for dept in response["ResponseData"]["Buses"]:
            buses.append(
                Departure(dept["Destination"], dept["DisplayTime"],
                          dept["LineNumber"]))
        return buses

    def set_endpoint(self, schema, key, site_id, time_window):
        self.endpoint = self.BASE_URL.format(schema=schema,
                                             key=key,
                                             siteid=site_id,
                                             timewindow=time_window)
        return endpoint

    def __init__(self, schema='json', siteid=None, timewindow='30'):
        self.log = GLogger().get_logger()
        self.log.info("Trafiklab object initiated")
        self.API_KEY = trafiklab_key.key
        if not siteid:
            self.home_station = self.SITE_ID_SICKLAKAJ
        else:
            self.home_station = siteid
        self.endpoint = self.BASE_URL.format(schema=schema,
                                             key=self.API_KEY,
                                             siteid=self.home_station,
                                             timewindow=timewindow)
 def __init__(self,
              schema='json',
              granularity='StopPoint'
              ):  #TODO: Use json parameter in endpoint string formatter
     self.log = GLogger(name=__name__).get_logger()
     self.granularity = granularity
     self.API_KEY = trafiklab_key.key_stops_and_lines
     self.endpoint = (
         'http://api.sl.se/api2/LineData.{1}?model={2}&key={0}'.format(
             self.API_KEY, schema, granularity))
 def __init__(self, schema='json', siteid=None, timewindow='30'):
     self.log = GLogger().get_logger()
     self.log.info("Trafiklab object initiated")
     self.API_KEY = trafiklab_key.key
     if not siteid:
         self.home_station = self.SITE_ID_SICKLAKAJ
     else:
         self.home_station = siteid
     self.endpoint = self.BASE_URL.format(schema=schema,
                                          key=self.API_KEY,
                                          siteid=self.home_station,
                                          timewindow=timewindow)
 def __init__(self):
     self.log = GLogger(name='StopLookuperLog').get_logger()
     self.API_KEY = trafiklab_key.key_platsuppslag
     self.endpoint = 'http://api.sl.se/api2/typeahead.{}?key={}&searchstring={}stationsonly=True&maxresults=10'
 def __init__(self):
     self.log = GLogger(name='StopLookuperLog').get_logger()
     self.API_KEY = trafiklab_key.key_close_stops
     self.endpoint = 'http://api.sl.se/api2/nearbystops.{}?key={}&originCoordLat={}&originCoordLong={}&maxresults={}&radius={}'
Beispiel #8
0
from flask_ask import Ask, question, statement, session, delegate
from flask import Flask, render_template
from traflab2 import Trafiklab
from glogger.gLogger import GLogger
import json
from collections import defaultdict, namedtuple
from DBHelper import DBHelper
from pprint import pprint

log = GLogger(handler='stream').get_logger()

app = Flask(__name__)
ask = Ask(app, '/')
db = DBHelper()

log.info("Log enabled")

# Build a dict of site id's to use when querying the main Trafiklab API
SITE_IDS = defaultdict(list)
with open('sl_Site_20180422-2113.json') as f:
    full_map = json.load(f)
    for site in full_map['ResponseData']['Result']:
        if not site['SiteName'].lower() in SITE_IDS:
            SITE_IDS[site['SiteName'].lower()].append(site['SiteId'])
            # SITE_IDS[site['StopPointName']].add((site['StopAreaNumber'],site['StopAreaTypeCode']))
    log.info('Built reference of SITE_IDs ({} entries)'.format(len(SITE_IDS)))


@ask.launch
def launch_skill():
    user_id = session.user.userId
Beispiel #9
0
 def __init__(self):
     self.log = GLogger(name=__name__).get_logger()
     self.log.info("Log initiated (DBHelper")