|
| 1 | +import re |
| 2 | + |
| 3 | + |
| 4 | +def resolve_path(path): |
| 5 | + urls = [(r'^$', welcome), |
| 6 | + (r'^add/(\d+)/(\d+)$', add), |
| 7 | + (r'^subtract/(\d+)/(\d+)$', subtract), |
| 8 | + (r'^divide/(\d+)/(\d+)$', divide), |
| 9 | + (r'^multiply/(\d+)/(\d+)$', multiply)] |
| 10 | + |
| 11 | + matchpath = path.lstrip('/') |
| 12 | + for regexp, func in urls: |
| 13 | + match = re.match(regexp, matchpath) |
| 14 | + if match is None: |
| 15 | + continue |
| 16 | + args = match.groups([]) |
| 17 | + return func, args |
| 18 | + # we get here if no url matches |
| 19 | + raise NameError |
| 20 | + |
| 21 | +def welcome(): |
| 22 | + return "<h1>welcome</h1>" |
| 23 | + |
| 24 | +def multiply(v1, v2): |
| 25 | + r = int(v1) * int(v2) |
| 26 | + return "<h1>result from multiplication: %d</h1>" %r |
| 27 | + |
| 28 | +def add(v1, v2): |
| 29 | + r = int(v1) + int(v2) |
| 30 | + return "<h1>result from addition: %d</h1>" % r |
| 31 | + |
| 32 | +def subtract(v1, v2): |
| 33 | + r = int(v1) - int(v2) |
| 34 | + return "<h1>result from subtraction: %d</h1>" % r |
| 35 | + |
| 36 | +def divide(v1, v2): |
| 37 | + r = int(v1) / int(v2) |
| 38 | + return "<h1>result from division: %d</h1>" % r |
| 39 | + |
| 40 | +def application(environ, start_response): |
| 41 | + headers = [("Content-type", "text/html")] |
| 42 | + try: |
| 43 | + path = environ.get('PATH_INFO', None) |
| 44 | + if path is None: |
| 45 | + raise NameError |
| 46 | + func, args = resolve_path(path) |
| 47 | + body = func(*args) |
| 48 | + status = "200 OK" |
| 49 | + except NameError: |
| 50 | + status = "404 Not Found" |
| 51 | + body = "<h1>Not Found</h1>" |
| 52 | + except ZeroDivisionError: |
| 53 | + status = "400 Bad Request" |
| 54 | + body = "<h1>Bad Request</h1>" |
| 55 | + except Exception: |
| 56 | + status = "500 Internal Server Error" |
| 57 | + body = "<h1>Internal Server Error</h1>" |
| 58 | + finally: |
| 59 | + headers.append(('Content-length', str(len(body)))) |
| 60 | + start_response(status, headers) |
| 61 | + return [body.encode('utf8')] |
| 62 | + |
| 63 | +if __name__ == '__main__': |
| 64 | + from wsgiref.simple_server import make_server |
| 65 | + srv = make_server('localhost', 8080, application) |
| 66 | + srv.serve_forever() |
0 commit comments