Add cronjob to fetch new timetable data from HSL

This commit is contained in:
Jan Tuomi
2017-01-20 15:07:26 +02:00
parent 332928ce30
commit 81a7f0a4a4
7 changed files with 51 additions and 25 deletions
+28
View File
@@ -0,0 +1,28 @@
from infoscreen.models import HSLDataModel
from django.conf import settings
import urllib.request
import json
class HSLFetcher:
def fetch(self):
location_coords = (2545565, 6675319)
src = urllib.request.urlopen(
"http://api.reittiopas.fi/hsl/prod/?userhash={}&request=stops_area&center_coordinate={},{}"
.format(settings.HSL_USERHASH, location_coords[0], location_coords[1]))\
.read().decode("utf-8")
data = json.loads(src)
arr = []
for element in data:
src = urllib.request.urlopen(
"http://api.reittiopas.fi/hsl/prod/?userhash={}&request=stop&code={}"
.format(settings.HSL_USERHASH, element['code'])).read().decode("utf-8")
parsed = json.loads(src)[0]
arr.append({"name": parsed['name_fi'], "lines": parsed['lines'],
"dist": element['dist'], "departures": parsed['departures']})
HSLDataModel.objects.create(data=json.dumps(arr))
+3 -24
View File
@@ -1,30 +1,9 @@
import json
import urllib.request
from django.conf import settings
from django.core.management.base import BaseCommand
from infoscreen.models import HSLDataModel
from infoscreen.hsl_fetcher import HSLFetcher
class Command(BaseCommand):
help = 'Loads HSL timetables and save to json file.'
def handle(self, *args, **options):
location_coords = (2545565, 6675319)
src = urllib.request.urlopen(
"http://api.reittiopas.fi/hsl/prod/?userhash={}&request=stops_area&center_coordinate={},{}"
.format(settings.HSL_USERHASH, location_coords[0], location_coords[1]))\
.read().decode("utf-8")
data = json.loads(src)
arr = []
for element in data:
src = urllib.request.urlopen(
"http://api.reittiopas.fi/hsl/prod/?userhash={}&request=stop&code={}"
.format(settings.HSL_USERHASH, element['code'])).read().decode("utf-8")
parsed = json.loads(src)[0]
arr.append({"name": parsed['name_fi'], "lines": parsed['lines'],
"dist": element['dist'], "departures": parsed['departures']})
HSLDataModel.objects.create(data=json.dumps(arr))
fetcher = HSLFetcher()
fetcher.fetch()