-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
199 lines (168 loc) · 5.51 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
from flask import Flask
from flask import jsonify
from flask import request
import datetime
import json
import model
from dateutil.parser import parse
from cassandra.cqlengine import connection
from flask.ext.cors import CORS
import pytz
from cassandra.cluster import Cluster
app = Flask(__name__)
CORS(app)
location = 'Jhongjheng District, Keelung City'
def addItem(q, temp, humid, rain, time, pm2_5, psi):
for i in q:
temp.append(round(i.basic.temp, 2))
humid.append(round(i.basic.humd * 100, 2))
time.append(pytz.timezone('Asia/Taipei').localize(i.time + datetime.timedelta(hours=8)).isoformat())
rain.append(max(i.rain.rain_10min, 0))
pm2_5.append(i.air.pm2_5)
psi.append(i.air.psi)
def getWindAnalysis(q):
res = []
for i in range(36):
res.append({
"d": i * 10,
"count": 0,
"avg": 0
})
res.append({
"d": None,
"count": 0,
"avg": 0
})
for i in q:
if i.basic.wind_dir_10min >= 0:
res[i.basic.wind_dir_10min / 10]['count'] += 1
res[i.basic.wind_dir_10min / 10]['avg'] += i.basic.wind_speed_10min
else:
res[36]['count'] += 1
for i in res:
if i['count'] is not 0:
i['avg'] /= i['count']
return res
@app.route('/', methods=['GET'])
def getWeather():
startTime = request.args.get('start', None)
endTime = request.args.get('end', None)
app.logger.debug(startTime)
app.logger.debug(endTime)
if startTime is not None and endTime is not None:
start = parse(startTime)
end = parse(endTime)
q = model.Weather.objects.filter(location=location).filter(model.Weather.time>=start).filter(model.Weather.time<=end).order_by('-time')
else:
# query for data
q = model.Weather.objects(location=location).limit(36).order_by('-time')
# prepare default response
temp = []
humid = []
time = []
rain = []
radarData = {}
metric = {}
predict = {}
pm2_5 = []
psi = []
metricTime = 0
# add item to response data
addItem(q, temp, humid, rain, time, pm2_5, psi)
if q.count() > 0:
radarData = {
"sun": q[0].value.sun,
"weather": q[0].value.weather,
"uv": q[0].value.uv,
"rain": q[0].value.rain,
"air": q[0].value.air,
"predict": q[0].value.predict
}
metric = {
'temp': round(q[0].basic.temp, 2),
'humd': round(q[0].basic.humd * 100, 2),
'uv': q[0].uv,
'pm2_5': q[0].air.pm2_5,
'psi': q[0].air.psi,
'sunset': datetime.time(q[0].sun.sunset.hour, q[0].sun.sunset.minute,
q[0].sun.sunset.second).isoformat(),
'sunrise': datetime.time(q[0].sun.sunrise.hour, q[0].sun.sunrise.minute,
q[0].sun.sunrise.second).isoformat(),
'wind': max(round(q[0].basic.wind_speed_10min, 2), 0)
}
metricTime = pytz.timezone('Asia/Taipei').localize(q[0].time + datetime.timedelta(hours=8)).isoformat()
predict = model.trasformPredictMetricsToInt(q[0].predict)
# ::-1 reverse list
resp = {
'tempHumidRainChart': {
'temp': temp[::-1],
'humid': humid[::-1],
'rain': rain[::-1],
'time': time[::-1]
},
'radar': radarData,
'metric': metric,
'windChart': getWindAnalysis(q),
'predict': predict,
'metricTime': metricTime,
'air': {
'pm2_5': pm2_5[::-1],
'psi': psi[::-1],
'time': time[::-1]
}
}
# app.logger.debug(q[0].predict)
print resp
return json.dumps(resp), 200, {'Content-Type': 'application/json'}
@app.route('/', methods=['POST'])
def addWeather():
app.logger.debug(request.data)
j = request.get_json()
app.logger.debug(j)
air = model.Air(psi=j['air']['psi'], pm2_5=j['air']['pm2_5'])
app.logger.debug(air)
sun = model.Sun(sunset=parse(j['sun']['sunset']).time(), sunrise=parse(j['sun']['sunrise']).time())
app.logger.debug(sun)
rain = model.Rain(
rain_10min=j['rain']['rain_10min'],
rain_60min=j['rain']['rain_60min'],
rain_3hr=j['rain']['rain_3hr'],
rain_6hr=j['rain']['rain_6hr'],
rain_12hr=j['rain']['rain_12hr'],
rain_24hr=j['rain']['rain_24hr']
)
app.logger.debug(rain)
basic = model.Basic(
wind_dir_10min=j['basic']['wind_dir_10min'],
wind_speed_10min=j['basic']['wind_speed_10min'],
humd=j['basic']['humd'],
temp=j['basic']['temp']
)
app.logger.debug(basic)
value = model.Value(
sun=j['value']['sun'],
weather=j['value']['weather'],
uv=j['value']['uv'],
rain=j['value']['rain'],
air=j['value']['air'],
predict=j['value']['predict'],
)
weather = model.Weather(
location=location,
time=parse(j['basic']['time']),
uv=j['uv'],
air=air,
sun=sun,
rain=rain,
basic=basic,
value=value,
predict=model.trasformPredictMetrics(j['predictMetrics'])
)
app.logger.debug(j['predictMetrics'])
app.logger.debug(weather)
weather.save()
return json.dumps({'success': True}), 200, {'Content-Type': 'application/json'}
if __name__ == '__main__':
# connect to test keyspace
connection.setup(['140.121.101.164'], "weather2")
app.run(debug=True, host='0.0.0.0')