forked from samirahmed/Zippopotamus-Cloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsgi.py
184 lines (148 loc) · 6.79 KB
/
wsgi.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
from bottle import route, default_app, static_file, view, response, run
from pymongo import Connection, json_util
from pymongo.database import Database
from bson.son import SON
import json
import os
class static_files():
'''
Serve Static Files for homepage. This is done with by
mapping all the /static/* folder to be served
'''
@route('/static/:path#.+#')
def serve(path):
return static_file(path, root='./static')
class index():
'''
Class for dynamic URLs and queries
'''
@route('/')
@view('index')
def homepage():
return {}
# @route('/:country', method='GET')
# def index(country):
# return '<b>%s listing</b>' % (country)
@route('/:country/:post', method='GET')
def index(country,post):
(isFound, results) = standard_query(country,post)
configure(response)
if ( isFound == False ) : # If standard query got >= 1 hit
response.status=404 # Set Status to a 404
return results # Return empty JSON String
@route('/nearby/:country/:post' , method='GET')
def find_nearby(country,post):
(isFound, result) = nearby_zip( country , post)
configure( response)
if (isFound == False) :
response.status=404
return result;
def configure(response):
'''
Configure:
Given a response dict, configure will
set the appropriate headers
'''
response['Content-Type']='application/json' # Specify MIME type to be JSON
response['charset']='UTF-8' # Speciify Charset for browser viewing
response['Access-Control-Allow-Origin']='*' # Enables CORS for XHR request
response['Vary']='Accept-Encoding'
pass
def nearby_zip(country,code):
'''
Looks up nearby postcodes given country and postal code
Returns results for JSON response
'''
post = list(db['nearby'].find({'post code' : code.upper(),
'country abbreviation': country.upper() }) )
if len(post) >= 1 :
lon = float( post[0]['longitude'] )
lat = float( post[0]['latitude'] )
( success, nearby ) = nearby_query( lat, lon )
if success:
response = { 'near latitude': lat, # Record the query lat
'near longitude': lon, # Record the query lat
'nearby' : nearby[1:] }
content = json.dumps( response , default=json_util.default )
return (True, content)
content = json.dumps({})
isFound = False;
return (isFound,content)
def nearby_coordinates( lat, lon):
'''
Looks up nearby postcodes given a latitude or longitude
Returns results formatted for Json Result
'''
(isFound, nearby ) = nearby_query( float(lon) , float(lat) )
if isFound :
results = { 'near latitude': lat, # Record the query lat.
'near longitude': lon, # Record the query lon.
'nearby': nearby[:10] }
content = json.dumps( results, default=json_util.default )
return ( True, content)
else :
content = json.dumps( {} )
return ( False, content )
def nearby_query(lat,lon):
'''
GeoSpatial Query,
Given a specific latitude or longitude, this returns the closes 11 zipcodes
'''
nearby = db.command( SON ( [ ('geoNear' , 'nearby') , # Geospatial search
('near' , [lon,lat] ) , # near given coordinates
('distanceMultiplier' , 3959 ) , # Return values in miles
('spherical', True ), # Spherical
('num', 11) ] ) ) # Results to return
if nearby['ok'] > 0 :
results = list()
for records in nearby['results'] :
places = records['obj']
places['distance'] = records['dis']
del places['loc'] # Remove Coordinate info
del places['_id'] # Remove mongo_id
del places['latitude'] # Remove string latitude
del places['longitude'] # Remove string long
del places['country'] # Remove country
del places['country abbreviation'] # Remove abbrevation
results.append(places)
return (True, results)
else :
isFound = False;
return (isFound,content);
def standard_query(country,code):
'''
Standard_query returns a JSON data if there are matching places, for a
given country abbreviation and zip code
'''
result = list(db['global'].find( {'country abbreviation':country.upper(),
'post code':code.upper() }) )
if len(result) < 1 :
content= json.dumps({}) # return empty json string
isFound = False # If no results found
return (isFound,content)
else:
country_name=result[0]['country'] # Capture country
country_abbv=result[0]['country abbreviation'] # Country abbrev.
post_code =result[0]['post code'] # and post code
isFound = True; # if Match found
for places in result: # Remove from each result
del places['_id'] # mongo id
del places['post code'] # post code
del places['country'] # country
del places['country abbreviation'] # country abbrev. information
content =json.dumps({ 'country':country_name, # Return unique fields
'country abbreviation':country_abbv,
'post code':post_code,
'places':result}, # Return a list of possible places
default=json_util.default) # Using pymongo json settings
return (isFound,content) # Return True and JSON results
# PRESENT GLOBAL
ZIP = 'zip'
NEARBY = 'nearby'
with open(os.path.expanduser('~/environment.json')) as f:
env = json.load(f) # Extract environment variables
connection = Connection( env['DOTCLOUD_DB_MONGODB_URL'] ) # Connect to be w/ env info
#connection = Connection()
db = Database(connection,'zip') # Get handle to ZIP db
application = default_app() # WSGI application
#run (host='localhost', port=8080) # Local Testing