def timezone():
code = request.args[\'q\'].decode(\'utf-8\')
logging.debug(\'Searching for {0}\'.format(code))
url = \'http://www.boutell.com/zipcodes/zipcode.zip\'
with tempfile.NamedTemporaryFile(prefix=\'usps\', suffix=\'.zip\') as out:
content = requests.get(url).content
out.write(content)
with zipfile.ZipFile(out) as zipfp:
zips = zipfp.read(\'zipcode.csv\')
codes = StringIO()
codes.write(os.linesep.join([s for s in zips.splitlines() if s.strip()]))
codes.seek(0)
zipreader = csv.DictReader(codes, fieldnames = ["zip","city","state","latitude","longitude","timezone","dst"])
for line in zipreader:
logging.debug(\'examining postal code {0}\'.format(line[\'zip\']))
if line[\'zip\'] == code:
return Response(__lookuptimezone(line), mimetype=\'text/plain\')
def __lookuptimezone(line):
if line[\'timezone\'].endswith(\'5\') and line[\'dst\'] == \'1\':
return \'EST5EDT\'
elif line[\'timezone\'].endswith(\'5\') and line[\'dst\'] == \'0\':
return \'EST5\'
elif line[\'timezone\'].endswith(\'6\') and line[\'dst\'] == \'1\':
return \'CST6CDT\'
elif line[\'timezone\'].endswith(\'6\') and line[\'dst\'] == \'0\':
return \'CST6\'
elif line[\'timezone\'].endswith(\'7\') and line[\'dst\'] == \'1\':
return \'MST7MDT\'
elif line[\'timezone\'].endswith(\'7\') and line[\'dst\'] == \'0\':
return \'MST7\'
elif line[\'timezone\'].endswith(\'8\') and line[\'dst\'] == \'1\':
return \'PST8PDT\'
elif line[\'timezone\'].endswith(\'8\') and line[\'dst\'] == \'0\':
return \'PST8\'
raise Exception, \'Invalid zipcdoe {0}\'.format(line)