-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
234 lines (184 loc) · 7.53 KB
/
app.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
# Import the dependencies.
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
import datetime as dt
#################################################
# Database Setup
#################################################
engine = create_engine("sqlite:///Resources/hawaii.sqlite")
# reflect an existing database into a new model
Base = automap_base()
# reflect the tables
Base.prepare(autoload_with=engine)
# Save references to each table
Measurement = Base.classes.measurement
Station = Base.classes.station
# Create our session (link) from Python to the DB
session = Session(engine)
#################################################
# Flask Setup
#################################################
app = Flask(__name__)
#################################################
# Flask Routes
#################################################
# Home Page
@app.route("/")
def home():
"""Homepage - List all available api routes."""
print("Request to homepage made...")
return (
f"Available Routes:<br/>"
"<br/>"
f"Static Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
"<br/>"
f"Dynamic Routes:<br/>"
f"/api/v1.0/yyyy-mm-dd<br/>"
f"/api/v1.0/yyyy-mm-dd/yyyy-mm-dd<br/>"
)
#----------------------------------------------------#
# Precipitation Page
@app.route("/api/v1.0/precipitation")
def precip():
"""Query 12 Months of Precipitation data - Return as JSON"""
print("Request to Precipitation data made...")
session
annum_prcp = session.query(Measurement.date,Measurement.prcp).filter(Measurement.date >= dt.date(2016,8,23)).order_by(Measurement.date.desc()).all()
session.close()
# Convert results to a dictionary
precip_annual = []
for date, prcp in annum_prcp:
precip_dict = {}
precip_dict[date] = prcp
precip_annual.append(precip_dict)
# JSONify the precip_annual list
return jsonify(precip_annual)
#----------------------------------------------------#
# Stations Page
@app.route("/api/v1.0/stations")
def stations():
"""Query a list of stations - Return as JSON"""
print("Request to Station list data made...")
session
stations = session.query(Station).all()
session.close()
# Convert results to a dictionary
station_list = []
for station in stations:
main_dict = {}
main_dict['Station'] = station.station
main_dict['Station_Details'] = {
"ID":station.id,
"Name":station.name,
"Latitude":station.latitude,
"Longitude":station.longitude,
"Elevation":station.elevation
}
station_list.append(main_dict)
# JSONify the Station_list list
return jsonify(station_list)
#----------------------------------------------------#
# Tobs Page
@app.route("/api/v1.0/tobs")
def tobs():
"""Query a most active station - Return tobs as JSON"""
print("Request for tobs of most active station made...")
session
tobs = session.query(Measurement.date, Measurement.tobs).filter(Measurement.station == "USC00519281").filter(Measurement.date >= dt.date(2016,8,18)).all()
session.close()
# Convert results to a dictionary
tobs_list = []
for date, tobs in tobs:
tobs_dict = {}
tobs_dict['Date'] = date
tobs_dict['Temperature'] = tobs
tobs_list.append(tobs_dict)
# JSONify the tobs_list list
return jsonify(tobs_list)
#----------------------------------------------------#
# Dynamic Page - Start Date only
@app.route("/api/v1.0/<start>")
def dynamic_1(start):
"""Dynamic query to retrieve data from the given start date - Min, Max, Avg Temp as JSON"""
print("Request for data with a start date given...")
# Convert start to date format
try:
# If the date given by the user contains "-" between Year, Month, Day - Remove the character
if (start.__contains__("-")):
start = start.replace("-","")
s_date = dt.datetime.strptime(start, '%Y%m%d')
session
# Variables for reference to temperature calculations
tmin = func.min(Measurement.tobs)
tmax = func.max(Measurement.tobs)
tavg = func.avg(Measurement.tobs)
data_request = session.query(tmin,tmax,tavg).filter(Measurement.date >= s_date).all()
session.close()
temp_data = []
for tmin, tmax, tavg in data_request:
temp_dict = {}
temp_dict['From_Date'] = start
temp_dict['Temp_Calcs'] = {
"Min Temperature" : tmin,
"Max Temperature" : tmax,
"Avg Temperature" : round(tavg,2)
}
temp_data.append(temp_dict)
# JSONify the temp_data list
return jsonify(temp_data)
# Exception handle if date given is in the incorrect format
except ValueError:
return jsonify({"error": f"The specified date '{start}' is not in the correct format.",
"note": f"Place a date in the format: yyyy-mm-dd or yyyymmdd"}), 404
#----------------------------------------------------#
# Dynamic Page - Start and End date
@app.route("/api/v1.0/<start>/<end>")
def dynamic_2(start,end):
"""Dynamic query to retrieve data from the given start date to given end date - Min, Max, Avg Temp as JSON"""
print("Request for data with a start date and end date given...")
# Convert start to date format
try:
# If the date given by the user contains "-" between Year, Month, Day - Remove the character
if (start.__contains__("-")) or (end.__contains__("-")):
start = start.replace("-","")
end = end.replace("-","")
s_date = dt.datetime.strptime(start, '%Y%m%d')
e_date = dt.datetime.strptime(end, '%Y%m%d')
# Check if the end date given is greater than the start date
if (e_date > s_date):
session
# Variables for reference to temperature calculations
tmin = func.min(Measurement.tobs)
tmax = func.max(Measurement.tobs)
tavg = func.avg(Measurement.tobs)
data_request = session.query(tmin,tmax,tavg).filter(Measurement.date >= s_date).filter(Measurement.date <= e_date).all()
session.close()
temp_data = []
for tmin, tmax, tavg in data_request:
temp_dict = {}
temp_dict['From_Date'] = start
temp_dict['To_Date'] = end
temp_dict['Temp_Calcs'] = {
"Min Temperature" : tmin,
"Max Temperature" : tmax,
"Avg Temperature" : round(tavg,2)
}
temp_data.append(temp_dict)
# JSONify the temp_data list
return jsonify(temp_data)
# If the end date is less than start date, return an error and prompt for dates to be changed
else:
return jsonify({"error":f"The end date '{end}' can not be less than the start date '{start}'. Please adjust your date values."}), 404
# Exception handle if date given is in the incorrect format
except ValueError:
return jsonify({"error": f"One of the specified dates '{start}' or '{end}' is not in the correct format.",
"note": f"Alter the dates to the format: yyyy-mm-dd or yyyymmdd"}), 404
if __name__ == '__main__':
app.run(debug=False)