box-o-sand/src/02-shipping/shipping.py

98 lines
2.6 KiB
Python

from __future__ import print_function
import sys
import cgi
from wsgiref.simple_server import make_server
def main(sysargs=sys.argv[:]):
port = 18080
server = make_server('0.0.0.0', port, shipping_app)
print('serving {0.__name__} on port {1}'.format(shipping_app, port))
server.serve_forever()
return 0
def shipping_app(environ, start_response):
path_info = environ.get('PATH_INFO', '').strip('/')
handler = {
'text': plaintext_handler,
'xml': xml_handler,
}.get(path_info)
if handler:
try:
return handler(environ, start_response)
except Exception:
start_response('500 Internal Server Error', [
('content-type', 'text/plain'),
])
return ['OUCH']
else:
ret = 'nothin at {0!r}'.format(path_info)
start_response('404 Not Found', [
('content-type', 'text/plain'),
('content-length', str(len(ret)))
])
return [ret]
def get_params(environ):
params = cgi.parse(fp=environ.get('wsgi.input'), environ=environ)
for key, value in params.iteritems():
if len(value) == 1:
params[key] = value[0]
return params
def xml_handler(environ, start_response):
params = get_params(environ)
zipcode = int(params.get('zipcode', 0))
pounds = int(params.get('pounds', 0))
ret = ['<options>']
for service, price in get_shipping_options(zipcode, pounds).iteritems():
ret.append('<option><service>{service}</service>'
'<price>{price}</price></option>'.format(**locals()))
ret.append('</options>')
body = '\n'.join(ret)
start_response('200 OK', [
('content-type', 'text/xml'),
('content-length', str(len(body)))
])
return [body]
def plaintext_handler(environ, start_response):
params = get_params(environ)
zipcode = int(params.get('zipcode', 0))
pounds = int(params.get('pounds', 0))
ret = []
for service, price in get_shipping_options(zipcode, pounds).iteritems():
ret.append('{service}: {price} USD'.format(**locals()))
body = '\n'.join(ret)
start_response('200 OK', [
('content-type', 'text/plain'),
('content-length', str(len(body)))
])
return [body]
def get_shipping_options(zipcode, pounds):
base_cost = (float(zipcode) / 10000.0) + (pounds * 5.0)
return {
"Next Day": int(base_cost * 4),
"Two Day Air": int(base_cost * 2),
"Saver Ground": int(base_cost)
}
if __name__ == '__main__':
sys.exit(main())
# vim:filetype=python