summaryrefslogtreecommitdiffstats
path: root/real.py
blob: e254c6915329273712aa5349161bd7826dd0b870 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from sys import stdin, exit
from datetime import datetime
import argparse
import json

import requests
import structlog
from jinja2 import Environment, FileSystemLoader


def get_data(logger, key, site_id):
    url = 'http://api.sl.se/api2/realtimedeparturesV4.json?key={}&SiteId={}'.format(key, site_id)
    res = requests.get(url)
    if res.status_code != requests.codes.ok:
        logger.error('Failed to get departure data',
                     status_code=res.status_code,
                     response=res.text)
        exit(1)

    write_data(res.text, site_id)

    return res.json()


def write_data(data, site_id):
    timestamp = datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
    with open('{}.{}.raw.json'.format(site_id, timestamp), 'w+') as f:
        f.write(data)


def write_html(data, site_id, stop_name, path):
    template = env.get_template('layout.html')
    with open('{}/{}.html'.format(path, site_id), 'w+') as f:
        f.write(template.render(data=data, stop_name=stop_name))


def write_txt(data, site_id, stop_name, path):
    template = env.get_template('layout.txt')
    with open('{}/{}.txt'.format(path, site_id), 'w+') as f:
        f.write(template.render(data=data, stop_name=stop_name))


if __name__ == '__main__':
    logger = structlog.get_logger()

    parser = argparse.ArgumentParser(description='Process the SL Realtime Departure API')
    parser.add_argument('-c', '--config', metavar='FILE', type=str, nargs='?',
                        required=True, help='path to config to use')
    parser.add_argument('--stdin', action='store_true')
    args = parser.parse_args()
    print(args)

    with open(args.config) as cf:
        config = json.load(cf)

    logger = logger.bind(site_id=config['site_id'],
                         stop_name=config['stop_name'])

    env = Environment(loader=FileSystemLoader('templates'),
                      trim_blocks=True,
                      lstrip_blocks=True)

    if args.stdin:
        data = json.load(stdin)
    else:
        data = get_data(logger, config['key'], config['site_id'])

    write_html(data, config['site_id'], config['stop_name'], config['output_path'])
    write_txt(data, config['site_id'], config['stop_name'], config['output_path'])