Created
December 7, 2020 07:57
-
-
Save EdwinTai/b4929d6667bbeafb4011a5a1ca5701a7 to your computer and use it in GitHub Desktop.
THSR python ptx api example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#https://ptx.transportdata.tw/PTX/ | |
from hashlib import sha1 | |
import hmac | |
from wsgiref.handlers import format_date_time | |
from datetime import datetime,date | |
from time import mktime | |
import base64 | |
from requests import request | |
from pprint import pprint | |
import json | |
#申請會員後才會拿到app_id, app_key,基於安全性,我把它放在我電腦裡的登錄檔 | |
import winreg | |
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"SOFTWARE\ptxauth") | |
app_id = winreg.QueryValueEx(key, 'app_id')[0] | |
app_key = winreg.QueryValueEx(key, 'app_key')[0] | |
class Auth(): | |
def __init__(self, app_id, app_key): | |
self.app_id = app_id | |
self.app_key = app_key | |
def get_auth_header(self): | |
xdate = format_date_time(mktime(datetime.now().timetuple())) | |
hashed = hmac.new(self.app_key.encode('utf8'), | |
('x-date: ' + xdate).encode('utf8'), sha1) | |
signature = base64.b64encode(hashed.digest()).decode() | |
authorization = 'hmac username="' + self.app_id + '", ' + \ | |
'algorithm="hmac-sha1", ' + \ | |
'headers="x-date", ' + \ | |
'signature="' + signature + '"' | |
return { | |
'Authorization': authorization, | |
'x-date': format_date_time(mktime(datetime.now().timetuple())), | |
'Accept - Encoding': 'gzip' | |
} | |
#https://ptx.transportdata.tw/MOTC?t=Rail&v=2#!/THSR/THSRApi_Station 查詢StationID,台北1000 台南1060 | |
if __name__ == '__main__': | |
a = Auth(app_id, app_key) | |
#根據from to StationID和日期,查出當天的班次 | |
fromstation = "1000" | |
tostation = "1060" | |
checkdate = date.today() | |
response = request( | |
'get', 'https://ptx.transportdata.tw/MOTC/v2/Rail/THSR/DailyTimetable/OD/%s/to/%s/%s?$format=JSON' % (fromstation, tostation, checkdate), headers=a.get_auth_header()) | |
schedule = json.loads(response.text) | |
sortedArray = sorted( | |
schedule, | |
key=lambda x: datetime.strptime(x["OriginStopTime"]["ArrivalTime"], '%H:%M'), reverse=False | |
) | |
#print(sortedArray) | |
for item in sortedArray: | |
traininfo = item["DailyTrainInfo"]["TrainNo"] | |
frm = item["OriginStopTime"]["DepartureTime"] | |
to = item["DestinationStopTime"]["ArrivalTime"] | |
FMT = '%H:%M' #計算行車時間 | |
print(traininfo,frm, to, datetime.strptime( | |
to, FMT)-datetime.strptime(frm, FMT)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment