-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache_runner.py
executable file
·55 lines (45 loc) · 1.63 KB
/
cache_runner.py
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
#!/usr/bin/env python3
import logging
from json import JSONDecodeError, dump, load
from os.path import abspath, dirname, join
from sys import exit, stderr, stdout
from time import sleep
from requests import get
from requests.exceptions import RequestException
logging.basicConfig(
format='[[%(levelname)s]] %(message)s',
stream=stdout,
level=logging.INFO,
)
try:
with open('config.json', 'r') as f:
CONFIG = load(f)
except (FileNotFoundError, JSONDecodeError):
logging.error('Please provide a config.json file in the current working directory')
exit(1)
STOPS = CONFIG['stop'].split(',')
KEY = CONFIG['key']
LIMIT = min(int(CONFIG.get('requests_max', 4900)), 4900)
MINUTES = CONFIG.get('request_minutes', 360) # 6 hours
OUTDIR = CONFIG.get('output_directory', abspath(dirname(__file__)))
while True:
for stop in STOPS:
try:
r = get('https://www.rmv.de/hapi/departureBoard?id={stop}&duration={minutes}&format=json&accessId={key}'.format(
stop=stop,
minutes=MINUTES,
key=KEY,
))
r.raise_for_status()
except RequestException as e:
logging.exception('[{}] {}'.format(stop, repr(e)))
else:
logging.info('[{}] fetched successfully'.format(stop))
with open(join(OUTDIR, '{}.json'.format(stop)), 'w') as f:
dump(r.json(), f, indent=4)
number_of_stops = len(STOPS)
sleep_time = 86400 / ( LIMIT / number_of_stops)
if sleep_time < 30:
sleep_time = 30
logging.info('waiting {} seconds before fetching again'.format(sleep_time))
sleep(sleep_time)