forked from Jorl17/open-elevation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
144 lines (116 loc) · 3.8 KB
/
server.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
import json
import bottle
from bottle import route, run, request, response, hook
from gdal_interfaces import GDALTileInterface
class InternalException(ValueError):
"""
Utility exception class to handle errors internally and return error codes to the client
"""
pass
"""
Initialize a global interface. This can grow quite large, because it has a cache.
"""
interface = GDALTileInterface('data/', 'data/summary.json')
interface.create_summary_json()
def get_elevation(lat, lng):
"""
Get the elevation at point (lat,lng) using the currently opened interface
:param lat:
:param lng:
:return:
"""
try:
elevation = interface.lookup(lat, lng)
except:
return {
'latitude': lat,
'longitude': lng,
'error': 'No such coordinate (%s, %s)' % (lat, lng)
}
return {
'latitude': lat,
'longitude': lng,
'elevation': elevation
}
@hook('after_request')
def enable_cors():
"""
Enable CORS support.
:return:
"""
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
def lat_lng_from_location(location_with_comma):
"""
Parse the latitude and longitude of a location in the format "xx.xxx,yy.yyy" (which we accept as a query string)
:param location_with_comma:
:return:
"""
try:
lat, lng = [float(i) for i in location_with_comma.split(',')]
return lat, lng
except:
raise InternalException(json.dumps({'error': 'Bad parameter format "%s".' % location_with_comma}))
def query_to_locations():
"""
Grab a list of locations from the query and turn them into [(lat,lng),(lat,lng),...]
:return:
"""
locations = request.query.locations
if not locations:
raise InternalException(json.dumps({'error': '"Locations" is required.'}))
return [lat_lng_from_location(l) for l in locations.split('|')]
def body_to_locations():
"""
Grab a list of locations from the body and turn them into [(lat,lng),(lat,lng),...]
:return:
"""
try:
locations = request.json.get('locations', None)
except Exception:
raise InternalException(json.dumps({'error': 'Invalid JSON.'}))
if not locations:
raise InternalException(json.dumps({'error': '"Locations" is required in the body.'}))
latlng = []
for l in locations:
try:
latlng += [ (l['latitude'],l['longitude']) ]
except KeyError:
raise InternalException(json.dumps({'error': '"%s" is not in a valid format.' % l}))
return latlng
def do_lookup(get_locations_func):
"""
Generic method which gets the locations in [(lat,lng),(lat,lng),...] format by calling get_locations_func
and returns an answer ready to go to the client.
:return:
"""
try:
locations = get_locations_func()
return {'results': [get_elevation(lat, lng) for (lat, lng) in locations]}
except InternalException as e:
response.status = 400
response.content_type = 'application/json'
return e.args[0]
# Base Endpoint
URL_ENDPOINT = '/api/v1/lookup'
# For CORS
@route(URL_ENDPOINT, method=['OPTIONS'])
def cors_handler():
return {}
@route(URL_ENDPOINT, method=['GET'])
def get_lookup():
"""
GET method. Uses query_to_locations.
:return:
"""
return do_lookup(query_to_locations)
@route(URL_ENDPOINT, method=['POST'])
def post_lookup():
"""
GET method. Uses body_to_locations.
:return:
"""
return do_lookup(body_to_locations)
#run(host='0.0.0.0', port=8080)
run(host='0.0.0.0', port=8080, server='gunicorn', workers=4)