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, 'crossdomain.xml': crossdomain_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(float(params.get('zipcode', 0))) pounds = int(float(params.get('pounds', 0))) ret = [''] for service, price in get_shipping_options(zipcode, pounds).iteritems(): ret.append(''.format(**locals())) ret.append('') 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(float(params.get('zipcode', 0))) pounds = int(float(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 crossdomain_xml_handler(environ, start_response): start_response('200 OK', [ ('content-type', 'text/xml'), ('content-length', str(len(XD_XML))), ]) return [XD_XML] XD_XML = """\ """ 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