forked from brandonmcfadd/cta-reliability
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
246 lines (216 loc) · 10.3 KB
/
api.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""cta-reliability API by Brandon McFadden"""
from datetime import datetime, timedelta
import os # Used to retrieve secrets in .env file
import json
from dotenv import load_dotenv # Used to Load Env Var
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.responses import HTMLResponse, StreamingResponse
from fastapi import Response
from fastapi.responses import PlainTextResponse
import redis.asyncio as redis
from fastapi_limiter import FastAPILimiter
from fastapi_limiter.depends import RateLimiter
from dateutil.relativedelta import relativedelta
import apihtml
app = FastAPI(docs_url=None)
security = HTTPBasic()
# Load .env variables
load_dotenv()
main_file_path = os.getenv('FILE_PATH')
main_file_path_json = os.getenv('FILE_PATH_JSON')
main_file_path_csv = os.getenv('FILE_PATH_CSV')
main_file_path_csv_month = os.getenv('FILE_PATH_CSV_MONTH')
def get_date(date_type):
"""formatted date shortcut"""
if date_type == "short":
date = datetime.strftime(datetime.now(), "%Y%m%d")
elif date_type == "hour":
date = datetime.strftime(datetime.now(), "%H")
elif date_type == "api-today":
date = datetime.strftime(datetime.now(), "%Y-%m-%d")
elif date_type == "api-yesterday":
date = datetime.strftime(datetime.now()-timedelta(days=1), "%Y-%m-%d")
elif date_type == "api-last-month":
date = datetime.strftime(datetime.now()-relativedelta(months=1), "%Y-%m")
elif date_type == "current":
date = datetime.strftime(datetime.now(), "%d %b %Y %H:%M:%S")
return date
def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
"""Used to verify Creds"""
file = open(file=main_file_path + 'cta-reliability/.tokens',
mode='r',
encoding='utf-8')
tokens = json.load(file)
try:
if credentials.username in tokens:
is_correct_username = True
else:
is_correct_username = False
reason = "Incorrect username or password"
except: # pylint: disable=bare-except
is_correct_username = False
reason = "Incorrect username or password"
try:
if credentials.password == tokens[credentials.username]["password"]:
is_correct_password = True
else:
is_correct_password = False
reason = "Incorrect username or password"
except: # pylint: disable=bare-except
is_correct_password = False
reason = "Incorrect username or password"
try:
if tokens[credentials.username]["disabled"] == "True":
is_enabled = False
reason = "Account Disabled"
else:
is_enabled = True
except: # pylint: disable=bare-except
is_enabled = True
reason = "Account Disabled"
if not (is_correct_username and is_correct_password and is_enabled):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=reason,
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
def generate_html_response_intro():
"""Used for Root Page"""
html_content = apihtml.MAIN_PAGE
return HTMLResponse(content=html_content, status_code=200)
def generate_html_response_error(date, endpoint, current_time):
"""Used for Error Page"""
html_content = f"""
<html>
<head>
<title>CTA Reliability API Error</title>
</head>
<body>
<h1>Error In CTA Reliability API Request</h1>
<p>Current System Time: {current_time}</p>
<p>Endpoint: {endpoint}{date}<br>
Unable to retrieve results for the date {date}<br><br>
If you are using the 'get_train_arrivals_by_day' endpoint, please note that data for the previous day is not loaded until ~01:00 CST.</p>
<p></p>
<p>Please refer to the documentation for assistance: <a href="http://rta-api.brandonmcfadden.com">RTA API Documentation</a></p>
</body>
</html>
"""
return HTMLResponse(content=html_content, status_code=200)
@app.on_event("startup")
async def startup():
"""Tells API to Prep redis for Rate Limit"""
redis_value = redis.from_url(
"redis://localhost", encoding="utf-8", decode_responses=True)
await FastAPILimiter.init(redis_value)
@app.get("/", dependencies=[Depends(RateLimiter(times=2, seconds=1))])
async def read_root():
"""Tells API to Display Root"""
return generate_html_response_intro()
@app.get("/api/", response_class=HTMLResponse, dependencies=[Depends(RateLimiter(times=2, seconds=1))])
async def documentation():
"""Tells API to Display Root"""
return generate_html_response_intro()
@app.get("/api/v1/get_daily_results/{date}", dependencies=[Depends(RateLimiter(times=2, seconds=1))])
async def return_results_for_date(date: str, token: str = Depends(get_current_username)):
"""Used to retrieve results"""
try:
json_file = main_file_path_json + "cta/" + date + ".json"
results = open(json_file, 'r', encoding="utf-8")
return Response(content=results.read(), media_type="application/json")
except: # pylint: disable=bare-except
endpoint = "http://rta-api.brandonmcfadden.com/api/v1/get_daily_results/"
return generate_html_response_error(date, endpoint, get_date("current"))
@app.get("/api/v2/cta/get_daily_results/{date}", dependencies=[Depends(RateLimiter(times=2, seconds=1))])
async def return_results_for_date_cta_v2(date: str, token: str = Depends(get_current_username)):
"""Used to retrieve results"""
if date == "today":
date = get_date("api-today")
elif date == "yesterday":
date = get_date("api-yesterday")
if date == "availability":
files_available = sorted((f for f in os.listdir(main_file_path_json + "cta/") if not f.startswith(".")), key=str.lower)
return files_available
else:
try:
json_file = main_file_path_json + "cta/" + date + ".json"
results = open(json_file, 'r', encoding="utf-8")
return Response(content=results.read(), media_type="application/json")
except: # pylint: disable=bare-except
endpoint = "http://rta-api.brandonmcfadden.com/api/v2/cta/get_daily_results/"
return generate_html_response_error(date, endpoint, get_date("current"))
@app.get("/api/v2/metra/get_daily_results/{date}", dependencies=[Depends(RateLimiter(times=2, seconds=1))])
async def return_results_for_date_metra_v2(date: str, token: str = Depends(get_current_username)):
"""Used to retrieve results"""
if date == "today":
date = get_date("api-today")
elif date == "yesterday":
date = get_date("api-yesterday")
if date == "availability":
files_available = sorted((f for f in os.listdir(main_file_path_json + "metra/") if not f.startswith(".")), key=str.lower)
return files_available
else:
try:
json_file = main_file_path_json + "metra/" + date + ".json"
results = open(json_file, 'r', encoding="utf-8")
return Response(content=results.read(), media_type="application/json")
except: # pylint: disable=bare-except
endpoint = "http://rta-api.brandonmcfadden.com/api/v2/metra/get_daily_results/"
return generate_html_response_error(date, endpoint, get_date("current"))
@app.get("/api/v2/cta/get_train_arrivals_by_day/{date}", dependencies=[Depends(RateLimiter(times=2, seconds=1))])
async def return_arrivals_for_date_cta_v2(date: str, token: str = Depends(get_current_username)):
"""Used to retrieve results"""
if date == "yesterday":
date = get_date("api-yesterday")
if date == "availability":
files_available = sorted((f for f in os.listdir(main_file_path_csv + "cta/") if not f.startswith(".")), key=str.lower)
return files_available
else:
try:
csv_file = main_file_path_csv + "cta/" + date + ".csv"
print(csv_file)
results = open(csv_file, 'r', encoding="utf-8")
return StreamingResponse(
results,
media_type="text/csv",
headers={
"Content-Disposition": f"attachment; filename=cta-arrivals-{date}.csv"}
)
except: # pylint: disable=bare-except
endpoint = "http://rta-api.brandonmcfadden.com/api/v2/cta/get_train_arrivals_by_day/"
return generate_html_response_error(date, endpoint, get_date("current"))
@app.get("/api/v2/cta/get_train_arrivals_by_month/{date}", dependencies=[Depends(RateLimiter(times=2, seconds=1))])
async def return_arrivals_for_date_cta_v2(date: str, token: str = Depends(get_current_username)):
"""Used to retrieve results"""
if date == "yesterday":
date = get_date("api-last-month")
if date == "availability":
files_available = sorted((f for f in os.listdir(main_file_path_csv_month + "cta/") if not f.startswith(".")), key=str.lower)
return files_available
else:
try:
csv_file = main_file_path_csv_month + "cta/" + date + ".csv"
print(csv_file)
results = open(csv_file, 'r', encoding="utf-8")
return StreamingResponse(
results,
media_type="text/csv",
headers={
"Content-Disposition": f"attachment; filename=cta-arrivals-{date}.csv"}
)
except: # pylint: disable=bare-except
endpoint = "http://rta-api.brandonmcfadden.com/api/v2/cta/get_train_arrivals_by_day/"
return generate_html_response_error(date, endpoint, get_date("current"))
@app.get("/api/v2/cta/headways", dependencies=[Depends(RateLimiter(times=2, seconds=1))])
async def return_special_station_json(token: str = Depends(get_current_username)):
"""Used to retrieve results"""
try:
json_file = main_file_path + "cta-reliability/train_arrivals/json/special-station.json"
print(json_file)
results = open(json_file, 'r', encoding="utf-8")
return Response(content=results.read(), media_type="application/json")
except: # pylint: disable=bare-except
endpoint = "http://rta-api.brandonmcfadden.com/api/v2/cta/headways"
return generate_html_response_error(get_date("current"), endpoint, get_date("current"))