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'])