-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
340 lines (289 loc) · 10.1 KB
/
api.py
File metadata and controls
340 lines (289 loc) · 10.1 KB
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import urllib.request
import urllib.parse
import urllib.error
from pathlib import Path
import json
from collections import namedtuple
Coordinate = namedtuple('Coordinate',['latitude','longitude'])
class ForwardGeoCodingAPI():
def __init__(self, location: str):
self.location = location
def get_point(self) -> dict | str:
params = urllib.parse.urlencode({
'q': self.location,
'format': 'jsonv2'
})
api_url = f'https://nominatim.openstreetmap.org/search?{params}'
try:
request = urllib.request.Request(
api_url,
headers = {'Referer': 'Edit this to your custom header, such as the website calling it'},
)
response = urllib.request.urlopen(request)
json_text = response.read().decode(encoding= 'utf-8')
json_dict = json.loads(json_text)
lat = json_dict[0].get('lat')
lon = json_dict[0].get('lon')
if response.status != 200:
print('FAILED')
print(response.status, api_url)
print('NOT 200')
return 'NOT 200'
except urllib.error.HTTPError as e:
print('FAILED')
print(e.code, e.url)
print('NOT 200')
return 'NOT 200'
except urllib.error.URLError as e:
print('FAILED')
print(api_url)
print('NETWORK')
return 'NETWORK'
except (json.JSONDecodeError, KeyError) as e:
print('FAILED')
print(api_url)
print('FORMAT')
return 'FORMAT'
#
except Exception as e:
print('FAILED')
print(api_url)
print('NOT 200')
return 'NOT 200'
else:
response.close()
return Coordinate(lat,lon)
class ForwardGeoCodingFile():
def __init__(self, path:str):
self.path = path
def get_point(self) -> dict:
try:
file = Path(self.path)
with open(file, mode ='r') as temp_file:
data = json.load(temp_file)
lat = data[0].get('lat')
lon = data[0].get('lon')
return Coordinate(lat, lon)
except FileNotFoundError:
print('FAILED')
print(file)
print('MISSING')
return 'MISSING'
except (json.JSONDecodeError, KeyError) as e:
print('FAILED')
print(self.path)
print('FORMAT')
return 'FORMAT'
except:
print('FAILED')
print(file)
print('MISSING')
return 'MISSING'
class WeatherReport:
def __init__(self, location:tuple):
self.location = location #tuple
def get_point(self):
lat = self.location[0]
long = self.location[1]
api_url = f'https://api.weather.gov/points/{lat},{long}'
try:
request = urllib.request.Request(
api_url,
headers = {'User-Agent':'WEBSITE NAME, PERSONAL HEADER',
'Accept': 'application/geo+json'}
)
response = urllib.request.urlopen(request)
json_text = response.read().decode(encoding= 'utf-8')
json_dict = json.loads(json_text)
response.close()
if response.status != 200:
print('FAILED')
print(response.status, api_url)
print('NOT 200')
return 'NOT 200'
except urllib.error.HTTPError as e:
print('FAILED')
if(e.code != '' ):
print(e.code, e.url)
elif(e.code == ''):
print(e.url)
if(e.code != 200):
print('NOT 200')
return 'NOT 200'
except urllib.error.URLError as e:
print('FAILED')
print(api_url)
print('NETWORK')
return 'NETWORK'
except json.JSONDecodeError as e:
print('FAILED')
print(api_url)
print('FORMAT')
return 'FORMAT'
except:
print('FAILED')
print(api_url)
print('NOT 200')
return 'NOT 200'
else:
response.close()
return json_dict
class HourlyReportAPI:
def __init__(self, url:str):
self.url = url #string
def get_point(self):
api_url = self.url.get('properties', {}).get('forecastHourly')
try:
request = urllib.request.Request(
api_url,
headers = {'User-Agent':'WEBSITE NAME, PERSONAL HEADER'},
)
response = urllib.request.urlopen(request)
json_text = response.read().decode(encoding= 'utf-8')
json_dict = json.loads(json_text)
response.close()
for period in json_dict['properties']['periods']:
period['startTime'],
period['temperatureUnit'], period['temperature'],
period['relativeHumidity']['value'], period['windSpeed'],
period['probabilityOfPrecipitation']['value']
if response.status != 200:
print('FAILED')
print(response.status, api_url)
print('NOT 200')
return 'NOT 200'
return json_dict
except urllib.error.HTTPError as e:
print('FAILED')
if(e.code != '' ):
print(e.code, e.url)
elif(e.code == ''):
print(e.url)
if(e.code != 200):
print('NOT 200')
return 'NOT 200'
except urllib.error.URLError as e:
print('FAILED')
print(api_url)
print('NETWORK')
return 'NETWORK'
except (json.JSONDecodeError, KeyError) as e:
print('FAILED')
print(api_url)
print('FORMAT')
return 'FORMAT'
except:
print('FAILED')
print(api_url)
print('NOT 200')
return 'NOT 200'
class HourlyReportFile:
def __init__(self, path:str):
self.path = path
def get_point(self) -> dict:
'''Opens a file, and returns the contents as a json dict'''
file = Path(self.path)
try:
with open(file, mode ='r') as temp_file:
data = json.load(temp_file)
# THis is there to make sure no missing fields. Will fail if it cant parse
for period in data['properties']['periods']:
period['startTime'],
period['temperatureUnit'], period['temperature'],
period['relativeHumidity']['value'], period['windSpeed'],
period['probabilityOfPrecipitation']['value']
return data
except FileNotFoundError:
print('FAILED')
print(file)
print('MISSING')
return 'MISSING'
except(json.JSONDecodeError, KeyError):
print('FAILED')
print(file)
print('FORMAT')
return 'FORMAT'
except:
print('FAILED')
print(file)
print('MISSING')
return 'MISSING'
class ReverseGeoCodingAPI:
def __init__(self, location:tuple):
self.location = location
def get_address(self) -> str:
lat = self.location[0]
long = self.location[1]
lat = round(self.location[0], 4)
long = round(self.location[1], 4)
params = urllib.parse.urlencode({
'lat': lat,
'lon': long,
'format': 'json'
})
api_url = f'https://nominatim.openstreetmap.org/reverse?{params}'
try:
request = urllib.request.Request(
api_url,
headers = {'Referer': 'Edit this to your custom header, such as the website calling it'},
)
response = urllib.request.urlopen(request)
json_text = response.read().decode(encoding= 'utf-8')
json_dict = json.loads(json_text)
if response.status != 200:
print('FAILED')
print(response.status, api_url)
print('NOT 200')
return 'NOT 200'
except urllib.error.HTTPError as e:
print('FAILED')
if(e.code != '' ):
print(e.code, e.url)
elif(e.code == ''):
print(e.url)
if(e.code != 200):
print('NOT 200')
return 'NOT 200'
except urllib.error.URLError as e:
print('FAILED')
print(api_url)
print('NETWORK')
return 'NETWORK'
except json.JSONDecodeError as e:
print('FAILED')
print(api_url)
print('FORMAT')
return 'FORMAT'
except:
print('FAILED')
print(api_url)
print('NOT 200')
return 'NOT 200'
else:
response.close()
return json_dict.get('display_name')
class ReverseGeoCodingFile:
def __init__(self, path: str):
self.path = path
def get_address(self):
'''Opens a file, and returns the contents as a json dict'''
file = Path(self.path)
try:
with open(file, mode ='r') as temp_file:
data = json.load(temp_file)
return data.get('display_name')
except FileNotFoundError:
print('FAILED')
print(file)
print('MISSING')
return 'MISSING'
except json.JSONDecodeError:
print('FAILED')
print(file)
print('FORMAT')
return 'FORMAT'
except:
print('FAILED')
print(file)
print('MISSING')
return 'MISSING'