-
Notifications
You must be signed in to change notification settings - Fork 17
/
zipapiserver.py
96 lines (80 loc) · 2.84 KB
/
zipapiserver.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
import time
import BaseHTTPServer
import urlparse
import json
import redis
import os
HOST_NAME = 'localhost'
PORT_NUMBER = int(os.environ.get('ZIPTASTIC_PORT', 80))
class ZipAPIServerHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(s):
# Get the zip from the data
qs = {}
path = s.path
the_zip = None
the_country = None
old_db = True
if path.startswith("/v2"):
old_db = False
path = path[3:]
if '?' in path:
path, tmp = path.split('?', 1)
qs = urlparse.parse_qs(tmp)
the_zip = qs.get('zip', [''])[0]
elif path:
the_zip = path.strip('/')
p = path.lstrip("/")
p = p.split("/", 2)
if len(p) == 2:
the_zip = p[1]
the_country = p[0]
if the_country is None:
the_country = 'US'
if the_country == 'CA':
the_zip = the_zip[:3].upper()
the_zip = the_zip.split('-')[0]
if the_zip:
# Query database with the ZIP and pull the city, state, country
r = redis.StrictRedis(host='localhost', port=6379, db=0)
if old_db:
location = r.hgetall(the_zip)
else:
location = r.hgetall("{0}:{1}".format(the_country, the_zip))
if len(location) > 0:
s.send_response(200)
s.send_header("Access-Control-Allow-Origin", "*")
s.send_header("Content-type", "application/json")
s.send_header("charset", "utf-8")
s.end_headers()
s.wfile.write(json.dumps(location))
else:
s.send_response(404)
s.send_header("Access-Control-Allow-Origin", "*")
s.send_header("Content-type", "text/plain")
s.send_header("charset", "utf-8")
s.end_headers()
s.wfile.write("{}")
else:
s.send_response(400)
s.send_header("Access-Control-Allow-Origin", "*")
s.send_header("Content-type", "application/json")
s.send_header("charset", "utf-8")
s.end_headers()
s.wfile.write("{}")
def do_OPTIONS(s):
s.send_response(200)
s.send_header("Access-Control-Allow-Origin", "*")
s.send_header("Access-Control-Allow-Headers", "X-Requested-With,X-Prototype-Version")
s.send_header("charset", "utf-8")
s.end_headers()
def start_server():
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), ZipAPIServerHandler)
#print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
if __name__ == '__main__':
start_server()