-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.py
57 lines (45 loc) · 1.55 KB
/
auth.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
56
57
import requests
from pprint import pprint
import json
from os import environ
from dotenv import load_dotenv
load_dotenv()
id = environ["TDX_ClientId"]
key = environ["TDX_ClientSecret"]
app_id = id
app_key = key
auth_url="https://tdx.transportdata.tw/auth/realms/TDXConnect/protocol/openid-connect/token"
url = "https://tdx.transportdata.tw/api/basic/v2/Rail/TRA/LiveTrainDelay?$top=30&$format=JSON"
class Auth():
def __init__(self, app_id, app_key):
self.app_id = app_id
self.app_key = app_key
def get_auth_header(self):
content_type = 'application/x-www-form-urlencoded'
grant_type = 'client_credentials'
return{
'content-type' : content_type,
'grant_type' : grant_type,
'client_id' : self.app_id,
'client_secret' : self.app_key
}
class data():
def __init__(self, app_id, app_key, auth_response):
self.app_id = app_id
self.app_key = app_key
self.auth_response = auth_response
def get_data_header(self):
auth_JSON = json.loads(self.auth_response.text)
access_token = auth_JSON.get('access_token')
return{
'authorization': 'Bearer '+access_token
}
if __name__ == '__main__':
a = Auth(app_id, app_key)
auth_response = requests.post(auth_url, a.get_auth_header())
d = data(app_id, app_key, auth_response)
data_response = requests.get(url, headers=d.get_data_header())
print(auth_response)
pprint(auth_response.text)
print(data_response)
pprint(data_response.text)