summaryrefslogtreecommitdiffstats
path: root/real.py
blob: d19b7e1f1806f6114d7b4c2e130f484b2415457e (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
from sys import stdin
from datetime import datetime
import argparse
import json

import requests
from jinja2 import Environment, FileSystemLoader


def get_data(key, site_id):
    url = 'http://api.sl.se/api2/realtimedeparturesV4.json?key={}&SiteId={}'.format(key, site_id)
    res = requests.get(url)
    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__':
    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)

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

    if args.stdin:
        data = json.load(stdin)
    else:
        data = get_data(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'])